]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/conf.rs
Auto merge of #9753 - smoelius:changelog, r=xFrednet
[rust.git] / clippy_lints / src / utils / conf.rs
1 //! Read configurations files.
2
3 #![allow(clippy::module_name_repetitions)]
4
5 use serde::de::{Deserializer, IgnoredAny, IntoDeserializer, MapAccess, Visitor};
6 use serde::Deserialize;
7 use std::error::Error;
8 use std::path::{Path, PathBuf};
9 use std::str::FromStr;
10 use std::{cmp, env, fmt, fs, io, iter};
11
12 #[rustfmt::skip]
13 const DEFAULT_DOC_VALID_IDENTS: &[&str] = &[
14     "KiB", "MiB", "GiB", "TiB", "PiB", "EiB",
15     "DirectX",
16     "ECMAScript",
17     "GPLv2", "GPLv3",
18     "GitHub", "GitLab",
19     "IPv4", "IPv6",
20     "ClojureScript", "CoffeeScript", "JavaScript", "PureScript", "TypeScript",
21     "NaN", "NaNs",
22     "OAuth", "GraphQL",
23     "OCaml",
24     "OpenGL", "OpenMP", "OpenSSH", "OpenSSL", "OpenStreetMap", "OpenDNS",
25     "WebGL",
26     "TensorFlow",
27     "TrueType",
28     "iOS", "macOS", "FreeBSD",
29     "TeX", "LaTeX", "BibTeX", "BibLaTeX",
30     "MinGW",
31     "CamelCase",
32 ];
33 const DEFAULT_DISALLOWED_NAMES: &[&str] = &["foo", "baz", "quux"];
34
35 /// Holds information used by `MISSING_ENFORCED_IMPORT_RENAMES` lint.
36 #[derive(Clone, Debug, Deserialize)]
37 pub struct Rename {
38     pub path: String,
39     pub rename: String,
40 }
41
42 #[derive(Clone, Debug, Deserialize)]
43 #[serde(untagged)]
44 pub enum DisallowedPath {
45     Simple(String),
46     WithReason { path: String, reason: Option<String> },
47 }
48
49 impl DisallowedPath {
50     pub fn path(&self) -> &str {
51         let (Self::Simple(path) | Self::WithReason { path, .. }) = self;
52
53         path
54     }
55
56     pub fn reason(&self) -> Option<&str> {
57         match self {
58             Self::WithReason {
59                 reason: Some(reason), ..
60             } => Some(reason),
61             _ => None,
62         }
63     }
64 }
65
66 /// Conf with parse errors
67 #[derive(Default)]
68 pub struct TryConf {
69     pub conf: Conf,
70     pub errors: Vec<Box<dyn Error>>,
71     pub warnings: Vec<Box<dyn Error>>,
72 }
73
74 impl TryConf {
75     fn from_error(error: impl Error + 'static) -> Self {
76         Self {
77             conf: Conf::default(),
78             errors: vec![Box::new(error)],
79             warnings: vec![],
80         }
81     }
82 }
83
84 #[derive(Debug)]
85 struct ConfError(String);
86
87 impl fmt::Display for ConfError {
88     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89         <String as fmt::Display>::fmt(&self.0, f)
90     }
91 }
92
93 impl Error for ConfError {}
94
95 fn conf_error(s: impl Into<String>) -> Box<dyn Error> {
96     Box::new(ConfError(s.into()))
97 }
98
99 macro_rules! define_Conf {
100     ($(
101         $(#[doc = $doc:literal])+
102         $(#[conf_deprecated($dep:literal, $new_conf:ident)])?
103         ($name:ident: $ty:ty = $default:expr),
104     )*) => {
105         /// Clippy lint configuration
106         pub struct Conf {
107             $($(#[doc = $doc])+ pub $name: $ty,)*
108         }
109
110         mod defaults {
111             $(pub fn $name() -> $ty { $default })*
112         }
113
114         impl Default for Conf {
115             fn default() -> Self {
116                 Self { $($name: defaults::$name(),)* }
117             }
118         }
119
120         impl<'de> Deserialize<'de> for TryConf {
121             fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
122                 deserializer.deserialize_map(ConfVisitor)
123             }
124         }
125
126         #[derive(Deserialize)]
127         #[serde(field_identifier, rename_all = "kebab-case")]
128         #[allow(non_camel_case_types)]
129         enum Field { $($name,)* third_party, }
130
131         struct ConfVisitor;
132
133         impl<'de> Visitor<'de> for ConfVisitor {
134             type Value = TryConf;
135
136             fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
137                 formatter.write_str("Conf")
138             }
139
140             fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error> where V: MapAccess<'de> {
141                 let mut errors = Vec::new();
142                 let mut warnings = Vec::new();
143                 $(let mut $name = None;)*
144                 // could get `Field` here directly, but get `str` first for diagnostics
145                 while let Some(name) = map.next_key::<&str>()? {
146                     match Field::deserialize(name.into_deserializer())? {
147                         $(Field::$name => {
148                             $(warnings.push(conf_error(format!("deprecated field `{}`. {}", name, $dep)));)?
149                             match map.next_value() {
150                                 Err(e) => errors.push(conf_error(e.to_string())),
151                                 Ok(value) => match $name {
152                                     Some(_) => errors.push(conf_error(format!("duplicate field `{}`", name))),
153                                     None => {
154                                         $name = Some(value);
155                                         // $new_conf is the same as one of the defined `$name`s, so
156                                         // this variable is defined in line 2 of this function.
157                                         $(match $new_conf {
158                                             Some(_) => errors.push(conf_error(concat!(
159                                                 "duplicate field `", stringify!($new_conf),
160                                                 "` (provided as `", stringify!($name), "`)"
161                                             ))),
162                                             None => $new_conf = $name.clone(),
163                                         })?
164                                     },
165                                 }
166                             }
167                         })*
168                         // white-listed; ignore
169                         Field::third_party => drop(map.next_value::<IgnoredAny>())
170                     }
171                 }
172                 let conf = Conf { $($name: $name.unwrap_or_else(defaults::$name),)* };
173                 Ok(TryConf { conf, errors, warnings })
174             }
175         }
176
177         #[cfg(feature = "internal")]
178         pub mod metadata {
179             use crate::utils::internal_lints::metadata_collector::ClippyConfiguration;
180
181             macro_rules! wrap_option {
182                 () => (None);
183                 ($x:literal) => (Some($x));
184             }
185
186             pub(crate) fn get_configuration_metadata() -> Vec<ClippyConfiguration> {
187                 vec![
188                     $(
189                         {
190                             let deprecation_reason = wrap_option!($($dep)?);
191
192                             ClippyConfiguration::new(
193                                 stringify!($name),
194                                 stringify!($ty),
195                                 format!("{:?}", super::defaults::$name()),
196                                 concat!($($doc, '\n',)*),
197                                 deprecation_reason,
198                             )
199                         },
200                     )+
201                 ]
202             }
203         }
204     };
205 }
206
207 define_Conf! {
208     /// Lint: Arithmetic.
209     ///
210     /// Suppress checking of the passed type names.
211     (arithmetic_side_effects_allowed: rustc_data_structures::fx::FxHashSet<String> = <_>::default()),
212     /// Lint: ENUM_VARIANT_NAMES, LARGE_TYPES_PASSED_BY_VALUE, TRIVIALLY_COPY_PASS_BY_REF, UNNECESSARY_WRAPS, UNUSED_SELF, UPPER_CASE_ACRONYMS, WRONG_SELF_CONVENTION, BOX_COLLECTION, REDUNDANT_ALLOCATION, RC_BUFFER, VEC_BOX, OPTION_OPTION, LINKEDLIST, RC_MUTEX.
213     ///
214     /// Suppress lints whenever the suggested change would cause breakage for other crates.
215     (avoid_breaking_exported_api: bool = true),
216     /// Lint: MANUAL_SPLIT_ONCE, MANUAL_STR_REPEAT, CLONED_INSTEAD_OF_COPIED, REDUNDANT_FIELD_NAMES, REDUNDANT_STATIC_LIFETIMES, FILTER_MAP_NEXT, CHECKED_CONVERSIONS, MANUAL_RANGE_CONTAINS, USE_SELF, MEM_REPLACE_WITH_DEFAULT, MANUAL_NON_EXHAUSTIVE, OPTION_AS_REF_DEREF, MAP_UNWRAP_OR, MATCH_LIKE_MATCHES_MACRO, MANUAL_STRIP, MISSING_CONST_FOR_FN, UNNESTED_OR_PATTERNS, FROM_OVER_INTO, PTR_AS_PTR, IF_THEN_SOME_ELSE_NONE, APPROX_CONSTANT, DEPRECATED_CFG_ATTR, INDEX_REFUTABLE_SLICE, MAP_CLONE, BORROW_AS_PTR, MANUAL_BITS, ERR_EXPECT, CAST_ABS_TO_UNSIGNED, UNINLINED_FORMAT_ARGS, MANUAL_CLAMP, MANUAL_LET_ELSE.
217     ///
218     /// The minimum rust version that the project supports
219     (msrv: Option<String> = None),
220     /// DEPRECATED LINT: BLACKLISTED_NAME.
221     ///
222     /// Use the Disallowed Names lint instead
223     #[conf_deprecated("Please use `disallowed-names` instead", disallowed_names)]
224     (blacklisted_names: Vec<String> = Vec::new()),
225     /// Lint: COGNITIVE_COMPLEXITY.
226     ///
227     /// The maximum cognitive complexity a function can have
228     (cognitive_complexity_threshold: u64 = 25),
229     /// DEPRECATED LINT: CYCLOMATIC_COMPLEXITY.
230     ///
231     /// Use the Cognitive Complexity lint instead.
232     #[conf_deprecated("Please use `cognitive-complexity-threshold` instead", cognitive_complexity_threshold)]
233     (cyclomatic_complexity_threshold: u64 = 25),
234     /// Lint: DISALLOWED_NAMES.
235     ///
236     /// The list of disallowed names to lint about. NB: `bar` is not here since it has legitimate uses. The value
237     /// `".."` can be used as part of the list to indicate, that the configured values should be appended to the
238     /// default configuration of Clippy. By default any configuration will replace the default value.
239     (disallowed_names: Vec<String> = super::DEFAULT_DISALLOWED_NAMES.iter().map(ToString::to_string).collect()),
240     /// Lint: DOC_MARKDOWN.
241     ///
242     /// The list of words this lint should not consider as identifiers needing ticks. The value
243     /// `".."` can be used as part of the list to indicate, that the configured values should be appended to the
244     /// default configuration of Clippy. By default any configuraction will replace the default value. For example:
245     /// * `doc-valid-idents = ["ClipPy"]` would replace the default list with `["ClipPy"]`.
246     /// * `doc-valid-idents = ["ClipPy", ".."]` would append `ClipPy` to the default list.
247     ///
248     /// Default list:
249     (doc_valid_idents: Vec<String> = super::DEFAULT_DOC_VALID_IDENTS.iter().map(ToString::to_string).collect()),
250     /// Lint: TOO_MANY_ARGUMENTS.
251     ///
252     /// The maximum number of argument a function or method can have
253     (too_many_arguments_threshold: u64 = 7),
254     /// Lint: TYPE_COMPLEXITY.
255     ///
256     /// The maximum complexity a type can have
257     (type_complexity_threshold: u64 = 250),
258     /// Lint: MANY_SINGLE_CHAR_NAMES.
259     ///
260     /// The maximum number of single char bindings a scope may have
261     (single_char_binding_names_threshold: u64 = 4),
262     /// Lint: BOXED_LOCAL, USELESS_VEC.
263     ///
264     /// The maximum size of objects (in bytes) that will be linted. Larger objects are ok on the heap
265     (too_large_for_stack: u64 = 200),
266     /// Lint: ENUM_VARIANT_NAMES.
267     ///
268     /// The minimum number of enum variants for the lints about variant names to trigger
269     (enum_variant_name_threshold: u64 = 3),
270     /// Lint: LARGE_ENUM_VARIANT.
271     ///
272     /// The maximum size of an enum's variant to avoid box suggestion
273     (enum_variant_size_threshold: u64 = 200),
274     /// Lint: VERBOSE_BIT_MASK.
275     ///
276     /// The maximum allowed size of a bit mask before suggesting to use 'trailing_zeros'
277     (verbose_bit_mask_threshold: u64 = 1),
278     /// Lint: DECIMAL_LITERAL_REPRESENTATION.
279     ///
280     /// The lower bound for linting decimal literals
281     (literal_representation_threshold: u64 = 16384),
282     /// Lint: TRIVIALLY_COPY_PASS_BY_REF.
283     ///
284     /// The maximum size (in bytes) to consider a `Copy` type for passing by value instead of by reference.
285     (trivial_copy_size_limit: Option<u64> = None),
286     /// Lint: LARGE_TYPE_PASS_BY_MOVE.
287     ///
288     /// The minimum size (in bytes) to consider a type for passing by reference instead of by value.
289     (pass_by_value_size_limit: u64 = 256),
290     /// Lint: TOO_MANY_LINES.
291     ///
292     /// The maximum number of lines a function or method can have
293     (too_many_lines_threshold: u64 = 100),
294     /// Lint: LARGE_STACK_ARRAYS, LARGE_CONST_ARRAYS.
295     ///
296     /// The maximum allowed size for arrays on the stack
297     (array_size_threshold: u64 = 512_000),
298     /// Lint: VEC_BOX.
299     ///
300     /// The size of the boxed type in bytes, where boxing in a `Vec` is allowed
301     (vec_box_size_threshold: u64 = 4096),
302     /// Lint: TYPE_REPETITION_IN_BOUNDS.
303     ///
304     /// The maximum number of bounds a trait can have to be linted
305     (max_trait_bounds: u64 = 3),
306     /// Lint: STRUCT_EXCESSIVE_BOOLS.
307     ///
308     /// The maximum number of bool fields a struct can have
309     (max_struct_bools: u64 = 3),
310     /// Lint: FN_PARAMS_EXCESSIVE_BOOLS.
311     ///
312     /// The maximum number of bool parameters a function can have
313     (max_fn_params_bools: u64 = 3),
314     /// Lint: WILDCARD_IMPORTS.
315     ///
316     /// Whether to allow certain wildcard imports (prelude, super in tests).
317     (warn_on_all_wildcard_imports: bool = false),
318     /// Lint: DISALLOWED_MACROS.
319     ///
320     /// The list of disallowed macros, written as fully qualified paths.
321     (disallowed_macros: Vec<crate::utils::conf::DisallowedPath> = Vec::new()),
322     /// Lint: DISALLOWED_METHODS.
323     ///
324     /// The list of disallowed methods, written as fully qualified paths.
325     (disallowed_methods: Vec<crate::utils::conf::DisallowedPath> = Vec::new()),
326     /// Lint: DISALLOWED_TYPES.
327     ///
328     /// The list of disallowed types, written as fully qualified paths.
329     (disallowed_types: Vec<crate::utils::conf::DisallowedPath> = Vec::new()),
330     /// Lint: UNREADABLE_LITERAL.
331     ///
332     /// Should the fraction of a decimal be linted to include separators.
333     (unreadable_literal_lint_fractions: bool = true),
334     /// Lint: UPPER_CASE_ACRONYMS.
335     ///
336     /// Enables verbose mode. Triggers if there is more than one uppercase char next to each other
337     (upper_case_acronyms_aggressive: bool = false),
338     /// Lint: MANUAL_LET_ELSE.
339     ///
340     /// Whether the matches should be considered by the lint, and whether there should
341     /// be filtering for common types.
342     (matches_for_let_else: crate::manual_let_else::MatchLintBehaviour =
343         crate::manual_let_else::MatchLintBehaviour::WellKnownTypes),
344     /// Lint: _CARGO_COMMON_METADATA.
345     ///
346     /// For internal testing only, ignores the current `publish` settings in the Cargo manifest.
347     (cargo_ignore_publish: bool = false),
348     /// Lint: NONSTANDARD_MACRO_BRACES.
349     ///
350     /// Enforce the named macros always use the braces specified.
351     ///
352     /// A `MacroMatcher` can be added like so `{ name = "macro_name", brace = "(" }`. If the macro
353     /// is could be used with a full path two `MacroMatcher`s have to be added one with the full path
354     /// `crate_name::macro_name` and one with just the macro name.
355     (standard_macro_braces: Vec<crate::nonstandard_macro_braces::MacroMatcher> = Vec::new()),
356     /// Lint: MISSING_ENFORCED_IMPORT_RENAMES.
357     ///
358     /// The list of imports to always rename, a fully qualified path followed by the rename.
359     (enforced_import_renames: Vec<crate::utils::conf::Rename> = Vec::new()),
360     /// Lint: DISALLOWED_SCRIPT_IDENTS.
361     ///
362     /// The list of unicode scripts allowed to be used in the scope.
363     (allowed_scripts: Vec<String> = vec!["Latin".to_string()]),
364     /// Lint: NON_SEND_FIELDS_IN_SEND_TY.
365     ///
366     /// Whether to apply the raw pointer heuristic to determine if a type is `Send`.
367     (enable_raw_pointer_heuristic_for_send: bool = true),
368     /// Lint: INDEX_REFUTABLE_SLICE.
369     ///
370     /// When Clippy suggests using a slice pattern, this is the maximum number of elements allowed in
371     /// the slice pattern that is suggested. If more elements would be necessary, the lint is suppressed.
372     /// For example, `[_, _, _, e, ..]` is a slice pattern with 4 elements.
373     (max_suggested_slice_pattern_length: u64 = 3),
374     /// Lint: AWAIT_HOLDING_INVALID_TYPE
375     (await_holding_invalid_types: Vec<crate::utils::conf::DisallowedPath> = Vec::new()),
376     /// Lint: LARGE_INCLUDE_FILE.
377     ///
378     /// The maximum size of a file included via `include_bytes!()` or `include_str!()`, in bytes
379     (max_include_file_size: u64 = 1_000_000),
380     /// Lint: EXPECT_USED.
381     ///
382     /// Whether `expect` should be allowed within `#[cfg(test)]`
383     (allow_expect_in_tests: bool = false),
384     /// Lint: UNWRAP_USED.
385     ///
386     /// Whether `unwrap` should be allowed in test cfg
387     (allow_unwrap_in_tests: bool = false),
388     /// Lint: DBG_MACRO.
389     ///
390     /// Whether `dbg!` should be allowed in test functions
391     (allow_dbg_in_tests: bool = false),
392     /// Lint: RESULT_LARGE_ERR.
393     ///
394     /// The maximum size of the `Err`-variant in a `Result` returned from a function
395     (large_error_threshold: u64 = 128),
396     /// Lint: MUTABLE_KEY.
397     ///
398     /// A list of paths to types that should be treated like `Arc`, i.e. ignored but
399     /// for the generic parameters for determining interior mutability
400     (ignore_interior_mutability: Vec<String> = Vec::from(["bytes::Bytes".into()])),
401 }
402
403 /// Search for the configuration file.
404 ///
405 /// # Errors
406 ///
407 /// Returns any unexpected filesystem error encountered when searching for the config file
408 pub fn lookup_conf_file() -> io::Result<Option<PathBuf>> {
409     /// Possible filename to search for.
410     const CONFIG_FILE_NAMES: [&str; 2] = [".clippy.toml", "clippy.toml"];
411
412     // Start looking for a config file in CLIPPY_CONF_DIR, or failing that, CARGO_MANIFEST_DIR.
413     // If neither of those exist, use ".".
414     let mut current = env::var_os("CLIPPY_CONF_DIR")
415         .or_else(|| env::var_os("CARGO_MANIFEST_DIR"))
416         .map_or_else(|| PathBuf::from("."), PathBuf::from);
417
418     let mut found_config: Option<PathBuf> = None;
419
420     loop {
421         for config_file_name in &CONFIG_FILE_NAMES {
422             if let Ok(config_file) = current.join(config_file_name).canonicalize() {
423                 match fs::metadata(&config_file) {
424                     Err(e) if e.kind() == io::ErrorKind::NotFound => {},
425                     Err(e) => return Err(e),
426                     Ok(md) if md.is_dir() => {},
427                     Ok(_) => {
428                         // warn if we happen to find two config files #8323
429                         if let Some(ref found_config_) = found_config {
430                             eprintln!(
431                                 "Using config file `{}`\nWarning: `{}` will be ignored.",
432                                 found_config_.display(),
433                                 config_file.display(),
434                             );
435                         } else {
436                             found_config = Some(config_file);
437                         }
438                     },
439                 }
440             }
441         }
442
443         if found_config.is_some() {
444             return Ok(found_config);
445         }
446
447         // If the current directory has no parent, we're done searching.
448         if !current.pop() {
449             return Ok(None);
450         }
451     }
452 }
453
454 /// Read the `toml` configuration file.
455 ///
456 /// In case of error, the function tries to continue as much as possible.
457 pub fn read(path: &Path) -> TryConf {
458     let content = match fs::read_to_string(path) {
459         Err(e) => return TryConf::from_error(e),
460         Ok(content) => content,
461     };
462     match toml::from_str::<TryConf>(&content) {
463         Ok(mut conf) => {
464             extend_vec_if_indicator_present(&mut conf.conf.doc_valid_idents, DEFAULT_DOC_VALID_IDENTS);
465             extend_vec_if_indicator_present(&mut conf.conf.disallowed_names, DEFAULT_DISALLOWED_NAMES);
466
467             conf
468         },
469         Err(e) => TryConf::from_error(e),
470     }
471 }
472
473 fn extend_vec_if_indicator_present(vec: &mut Vec<String>, default: &[&str]) {
474     if vec.contains(&"..".to_string()) {
475         vec.extend(default.iter().map(ToString::to_string));
476     }
477 }
478
479 const SEPARATOR_WIDTH: usize = 4;
480
481 // Check whether the error is "unknown field" and, if so, list the available fields sorted and at
482 // least one per line, more if `CLIPPY_TERMINAL_WIDTH` is set and allows it.
483 pub fn format_error(error: Box<dyn Error>) -> String {
484     let s = error.to_string();
485
486     if_chain! {
487         if error.downcast::<toml::de::Error>().is_ok();
488         if let Some((prefix, mut fields, suffix)) = parse_unknown_field_message(&s);
489         then {
490             use fmt::Write;
491
492             fields.sort_unstable();
493
494             let (rows, column_widths) = calculate_dimensions(&fields);
495
496             let mut msg = String::from(prefix);
497             for row in 0..rows {
498                 writeln!(msg).unwrap();
499                 for (column, column_width) in column_widths.iter().copied().enumerate() {
500                     let index = column * rows + row;
501                     let field = fields.get(index).copied().unwrap_or_default();
502                     write!(
503                         msg,
504                         "{:SEPARATOR_WIDTH$}{field:column_width$}",
505                         " "
506                     )
507                     .unwrap();
508                 }
509             }
510             write!(msg, "\n{suffix}").unwrap();
511             msg
512         } else {
513             s
514         }
515     }
516 }
517
518 // `parse_unknown_field_message` will become unnecessary if
519 // https://github.com/alexcrichton/toml-rs/pull/364 is merged.
520 fn parse_unknown_field_message(s: &str) -> Option<(&str, Vec<&str>, &str)> {
521     // An "unknown field" message has the following form:
522     //   unknown field `UNKNOWN`, expected one of `FIELD0`, `FIELD1`, ..., `FIELDN` at line X column Y
523     //                                           ^^      ^^^^                     ^^
524     if_chain! {
525         if s.starts_with("unknown field");
526         let slices = s.split("`, `").collect::<Vec<_>>();
527         let n = slices.len();
528         if n >= 2;
529         if let Some((prefix, first_field)) = slices[0].rsplit_once(" `");
530         if let Some((last_field, suffix)) = slices[n - 1].split_once("` ");
531         then {
532             let fields = iter::once(first_field)
533                 .chain(slices[1..n - 1].iter().copied())
534                 .chain(iter::once(last_field))
535                 .collect::<Vec<_>>();
536             Some((prefix, fields, suffix))
537         } else {
538             None
539         }
540     }
541 }
542
543 fn calculate_dimensions(fields: &[&str]) -> (usize, Vec<usize>) {
544     let columns = env::var("CLIPPY_TERMINAL_WIDTH")
545         .ok()
546         .and_then(|s| <usize as FromStr>::from_str(&s).ok())
547         .map_or(1, |terminal_width| {
548             let max_field_width = fields.iter().map(|field| field.len()).max().unwrap();
549             cmp::max(1, terminal_width / (SEPARATOR_WIDTH + max_field_width))
550         });
551
552     let rows = (fields.len() + (columns - 1)) / columns;
553
554     let column_widths = (0..columns)
555         .map(|column| {
556             if column < columns - 1 {
557                 (0..rows)
558                     .map(|row| {
559                         let index = column * rows + row;
560                         let field = fields.get(index).copied().unwrap_or_default();
561                         field.len()
562                     })
563                     .max()
564                     .unwrap()
565             } else {
566                 // Avoid adding extra space to the last column.
567                 0
568             }
569         })
570         .collect::<Vec<_>>();
571
572     (rows, column_widths)
573 }