Visual Studio Code, rebuilt in Rust
Rust
//! Test coverage of a run task: testCoverage.ts `TestCoverage` (the files' coverage in a prefix tree by URI path,
//! computed for the folders above them), testTypes.ts `CoverageDetails`, codeCoverageDecorations.ts
//! `CoverageDetailsModel` (the editor's non-overlapping ranges) and codeCoverageDisplayUtils.ts.
use std::collections::{BTreeMap, BTreeSet, HashMap};
use serde_json::Value;
#[cfg(test)]
mod tests;
/// testTypes.ts `ICoverageCount`.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct CoverageCount {
pub covered: u64,
pub total: u64,
}
impl CoverageCount {
fn from_value(value: &Value) -> Option<Self> {
Some(CoverageCount { covered: value["covered"].as_u64()?, total: value["total"].as_u64()? })
}
/// codeCoverageDisplayUtils.ts `percent`.
pub fn percent(self) -> f64 {
if self.total == 0 { 1. } else { (self.covered as f64 / self.total as f64).clamp(0., 1.) }
}
}
/// testCoverage.ts `getTotalCoveragePercent`.
pub fn total_coverage_percent(statement: CoverageCount, branch: Option<CoverageCount>, declaration: Option<CoverageCount>) -> f64 {
let mut numerator = statement.covered;
let mut denominator = statement.total;
for count in [branch, declaration].into_iter().flatten() {
numerator += count.covered;
denominator += count.total;
}
if denominator == 0 { 1. } else { numerator as f64 / denominator as f64 }
}
/// A URI's `UriComponents` parts the tree keys on.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CoverageUri {
pub scheme: String,
pub authority: String,
pub path: String,
}
impl CoverageUri {
pub fn from_value(value: &Value) -> Self {
let text = |key: &str| value[key].as_str().unwrap_or_default().to_owned();
CoverageUri { scheme: text("scheme"), authority: text("authority"), path: text("path") }
}
pub fn file(path: &str) -> Self {
CoverageUri { scheme: "file".into(), authority: String::new(), path: path.to_owned() }
}
/// resources.ts `basenameOrAuthority`.
pub fn basename(&self) -> &str {
match self.path.rsplit('/').next() {
Some(name) if !name.is_empty() => name,
_ => &self.authority,
}
}
/// The `URI.toString()` the coverage view sorts files by (without its percent-encoding).
pub fn to_uri_string(&self) -> String {
format!("{}://{}{}", self.scheme, self.authority, self.path)
}
}
/// Which of testCoverage.ts's `AbstractFileCoverage` classes a tree node holds.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CoverageKind {
/// `FileCoverage`: a file the extension reported.
File,
/// `ComputedFileCoverage`: a folder's sum of the files below it.
Computed,
/// `BypassedFileCoverage`: a node of `filterTreeForTest`, without counts.
Bypassed,
}
/// `AbstractFileCoverage`.
#[derive(Clone, Debug, PartialEq)]
pub struct FileCoverage {
pub kind: CoverageKind,
/// The extension host's id for `$getCoverageDetails`; a folder's is a counter.
pub id: String,
pub uri: CoverageUri,
pub statement: CoverageCount,
pub branch: Option<CoverageCount>,
pub declaration: Option<CoverageCount>,
/// `perTestData`: the tests that ran code in the file (or folder).
pub per_test: BTreeSet<String>,
}
impl FileCoverage {
/// `tpc`.
pub fn total_percent(&self) -> f64 {
total_coverage_percent(self.statement, self.branch, self.declaration)
}
}
/// An `IPrefixTreeNode` of a coverage tree: a path segment's node, keyed by the segment in its parent.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct CoverageNode {
pub value: Option<FileCoverage>,
pub children: BTreeMap<String, CoverageNode>,
}
impl CoverageNode {
/// `WellDefinedPrefixTree.values`.
pub fn values(&self) -> Vec<&FileCoverage> {
let mut values = Vec::new();
let mut stack: Vec<&CoverageNode> = vec![self];
while let Some(node) = stack.pop() {
values.extend(node.value.as_ref());
stack.extend(node.children.values());
}
values
}
}
/// `IFileCoverage.Serialized` from `$appendCoverage`.
#[derive(Clone, Debug, PartialEq)]
pub struct SerializedFileCoverage {
pub id: String,
pub uri: CoverageUri,
pub test_ids: Option<Vec<String>>,
pub statement: CoverageCount,
pub branch: Option<CoverageCount>,
pub declaration: Option<CoverageCount>,
}
impl SerializedFileCoverage {
pub fn from_value(value: &Value) -> Option<Self> {
Some(SerializedFileCoverage {
id: value["id"].as_str()?.to_owned(),
uri: CoverageUri::from_value(&value["uri"]),
test_ids: value["testIds"].as_array().map(|ids| ids.iter().filter_map(Value::as_str).map(str::to_owned).collect()),
statement: CoverageCount::from_value(&value["statement"])?,
branch: CoverageCount::from_value(&value["branch"]),
declaration: CoverageCount::from_value(&value["declaration"]),
})
}
}
/// The details of a file for the whole run (`None`) or one test, from `$getCoverageDetails`; `None` while loading.
pub type DetailsKey = (CoverageUri, Option<String>);
/// testCoverage.ts `TestCoverage`: one task's coverage.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TestCoverage {
pub tree: CoverageNode,
pub details: HashMap<DetailsKey, Option<Vec<CoverageDetail>>>,
next_id: u64,
}
impl TestCoverage {
/// `allPerTestIDs`: the tests of the top nodes' per-test data, each once.
pub fn all_per_test_ids(&self) -> Vec<String> {
let mut seen = BTreeSet::new();
let mut ids = Vec::new();
for root in self.tree.children.values() {
for id in root.value.iter().flat_map(|value| &value.per_test) {
if seen.insert(id.clone()) {
ids.push(id.clone());
}
}
}
ids
}
/// `append`: sets the file's node and adds the change of its counts to every folder above it.
pub fn append(&mut self, coverage: &SerializedFileCoverage) {
let previous = self.computed_for_uri(&coverage.uri).cloned();
let canonical = tree_path(&coverage.uri, true);
let path = tree_path(&coverage.uri, false);
let mut node = &mut self.tree;
for (depth, segment) in path.iter().enumerate() {
node = node.children.entry(segment.clone()).or_default();
if depth + 1 == canonical.len() {
match &mut node.value {
Some(value) => {
value.id = coverage.id.clone();
value.statement = coverage.statement;
value.branch = coverage.branch;
value.declaration = coverage.declaration;
}
None => {
node.value = Some(FileCoverage { kind: CoverageKind::File, id: coverage.id.clone(), uri: coverage.uri.clone(), statement: coverage.statement, branch: coverage.branch, declaration: coverage.declaration, per_test: BTreeSet::new() });
}
}
} else {
match &mut node.value {
// The folder starts with a copy of the first file's counts.
None => {
let id = self.next_id.to_string();
self.next_id += 1;
let uri = tree_path_to_uri(&canonical[..=depth]);
node.value = Some(FileCoverage { kind: CoverageKind::Computed, id, uri, statement: coverage.statement, branch: coverage.branch, declaration: coverage.declaration, per_test: BTreeSet::new() });
}
Some(value) => {
let old = previous.as_ref();
add_delta(&mut value.statement, Some(coverage.statement), old.map(|old| old.statement));
apply_delta(&mut value.branch, coverage.branch, old.and_then(|old| old.branch));
apply_delta(&mut value.declaration, coverage.declaration, old.and_then(|old| old.declaration));
}
}
}
if let Some(ids) = &coverage.test_ids {
node.value.as_mut().expect("set above").per_test.extend(ids.iter().cloned());
}
}
}
/// `filterTreeForTest`: the paths of the files the test ran code in, without counts.
pub fn filter_tree_for_test(&self, test_id: &str) -> CoverageNode {
let mut tree = CoverageNode::default();
for file in self.tree.values().into_iter().filter(|value| value.kind == CoverageKind::File && value.per_test.contains(test_id)) {
let canonical = tree_path(&file.uri, true);
let mut node = &mut tree;
for (depth, segment) in tree_path(&file.uri, false).iter().enumerate() {
node = node.children.entry(segment.clone()).or_default();
if node.value.is_none() {
let uri = tree_path_to_uri(&canonical[..=depth]);
node.value = Some(FileCoverage { kind: CoverageKind::Bypassed, id: String::new(), uri, statement: CoverageCount::default(), branch: None, declaration: None, per_test: BTreeSet::new() });
}
}
}
tree
}
/// `getUri`: a file the extension reported.
pub fn file(&self, uri: &CoverageUri) -> Option<&FileCoverage> {
self.computed_for_uri(uri).filter(|value| value.kind == CoverageKind::File)
}
/// `getComputedForUri`.
pub fn computed_for_uri(&self, uri: &CoverageUri) -> Option<&FileCoverage> {
let mut node = &self.tree;
for segment in tree_path(uri, false) {
node = node.children.get(&segment)?;
}
node.value.as_ref()
}
}
/// `applyDelta`: a missing count takes the file's, a present one adds the change since the file's previous report.
fn apply_delta(target: &mut Option<CoverageCount>, new: Option<CoverageCount>, old: Option<CoverageCount>) {
match target {
None => *target = new,
Some(count) => add_delta(count, new, old),
}
}
fn add_delta(count: &mut CoverageCount, new: Option<CoverageCount>, old: Option<CoverageCount>) {
let (new, old) = (new.unwrap_or_default(), old.unwrap_or_default());
count.covered = (count.covered + new.covered).saturating_sub(old.covered);
count.total = (count.total + new.total).saturating_sub(old.total);
}
/// `treePathForUri`: scheme, authority and the path's segments; the non-canonical path is lower case where the
/// file system ignores case (`extUri.ignorePathCasing`, the macOS `file` scheme).
fn tree_path(uri: &CoverageUri, canonical: bool) -> Vec<String> {
let path = if !canonical && uri.scheme == "file" && cfg!(target_os = "macos") { uri.path.to_lowercase() } else { uri.path.clone() };
let mut segments = vec![uri.scheme.clone(), uri.authority.clone()];
segments.extend(path.split('/').map(str::to_owned));
segments
}
fn tree_path_to_uri(path: &[String]) -> CoverageUri {
CoverageUri { scheme: path[0].clone(), authority: path.get(1).cloned().unwrap_or_default(), path: path.get(2..).map(|rest| rest.join("/")).unwrap_or_default() }
}
/// configuration.ts `TestingDisplayedCoveragePercent`, the `testing.displayedCoveragePercent` values.
pub fn displayed_stat(statement: CoverageCount, branch: Option<CoverageCount>, declaration: Option<CoverageCount>, method: &str) -> f64 {
match method {
"statement" => statement.percent(),
"minimum" => {
let mut value = statement.percent();
for count in [branch, declaration].into_iter().flatten() {
value = value.min(count.percent());
}
value
}
_ => total_coverage_percent(statement, branch, declaration),
}
}
/// codeCoverageDisplayUtils.ts `displayPercent`: at precision 0, less than all shows 99%, not a rounded-up 100%.
pub fn display_percent(value: f64, precision: usize) -> String {
let display = format!("{:.precision$}", value * 100.);
if value < 1. - 10e-8 && display == "100" {
return format!("{}%", 100. - 10f64.powi(-(precision as i32)));
}
format!("{display}%")
}
/// `getCoverageColor`: the closest `testing.coverageBarThresholds` threshold at or below the percent, red without one.
pub fn coverage_color(percent: f64, thresholds: &Value) -> &'static str {
let mut best = "charts.red";
let mut distance = percent;
for (key, color) in [("red", "charts.red"), ("yellow", "charts.yellow"), ("green", "charts.green")] {
let threshold = thresholds[key].as_f64().unwrap_or(0.) / 100.;
if threshold != 0. && percent >= threshold && percent - threshold < distance {
best = color;
distance = percent - threshold;
}
}
best
}
/// A 1-based `IPosition`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct CoveragePosition {
pub line: u32,
pub column: u32,
}
/// An `IRange`, its ends in order as range.ts's constructor puts them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CoverageRange {
pub start: CoveragePosition,
pub end: CoveragePosition,
}
impl CoverageRange {
pub fn new(a: CoveragePosition, b: CoveragePosition) -> Self {
if a <= b { CoverageRange { start: a, end: b } } else { CoverageRange { start: b, end: a } }
}
pub fn is_empty(&self) -> bool {
self.start == self.end
}
pub fn contains(&self, position: CoveragePosition) -> bool {
self.start <= position && position <= self.end
}
/// `IRange` or `IPosition` from the wire; a position is codeCoverageDecorations.ts `tidyLocation`'s rest of its line.
fn from_location(value: &Value) -> Option<Self> {
let number = |key: &str| value[key].as_u64().map(|number| number as u32);
if let Some(line) = number("lineNumber") {
let start = CoveragePosition { line, column: number("column")? };
return Some(CoverageRange::new(start, CoveragePosition { line, column: 0x7FFF_FFFF }));
}
let start = CoveragePosition { line: number("startLineNumber")?, column: number("startColumn")? };
Some(CoverageRange::new(start, CoveragePosition { line: number("endLineNumber")?, column: number("endColumn")? }))
}
}
/// A detail's `count`: how often it ran, or whether.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum HitCount {
Times(u64),
Ran(bool),
}
impl HitCount {
fn from_value(value: &Value) -> Self {
match value {
Value::Bool(ran) => HitCount::Ran(*ran),
count => HitCount::Times(count.as_u64().unwrap_or(0)),
}
}
pub fn is_hit(self) -> bool {
self != HitCount::Times(0) && self != HitCount::Ran(false)
}
/// `+hits` of a count or a boolean.
pub fn as_number(self) -> u64 {
match self {
HitCount::Times(times) => times,
HitCount::Ran(ran) => ran as u64,
}
}
}
/// `IBranchCoverage`.
#[derive(Clone, Debug, PartialEq)]
pub struct BranchCoverage {
pub count: HitCount,
pub label: Option<String>,
pub location: Option<CoverageRange>,
}
/// testTypes.ts `DetailType`, the tie order of the details model.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum DetailType {
Declaration,
Statement,
Branch,
}
/// `CoverageDetails.Serialized`: an `IDeclarationCoverage` (with a name) or an `IStatementCoverage`.
#[derive(Clone, Debug, PartialEq)]
pub struct CoverageDetail {
pub kind: DetailType,
pub name: String,
pub count: HitCount,
pub location: CoverageRange,
/// The wire location was an `IPosition`, which holds no other detail.
pub position: bool,
pub branches: Vec<BranchCoverage>,
}
impl CoverageDetail {
pub fn from_value(value: &Value) -> Option<Self> {
let kind = if value["type"].as_u64()? == 0 { DetailType::Declaration } else { DetailType::Statement };
let branches = value["branches"].as_array().into_iter().flatten().map(|branch| BranchCoverage {
count: HitCount::from_value(&branch["count"]),
label: branch["label"].as_str().map(str::to_owned),
location: CoverageRange::from_location(&branch["location"]),
});
Some(CoverageDetail { kind, name: value["name"].as_str().unwrap_or_default().to_owned(), count: HitCount::from_value(&value["count"]), location: CoverageRange::from_location(&value["location"])?, position: value["location"]["lineNumber"].is_u64(), branches: branches.collect() })
}
/// testCoverageView.ts `DeclarationCoverageNode.contains`: `containsRange`, or `containsPosition` of a position.
fn contains(&self, other: &CoverageDetail) -> bool {
let end = if other.position { other.location.start } else { other.location.end };
!self.position && self.location.contains(other.location.start) && self.location.contains(end)
}
}
/// testCoverageView.ts `DeclarationCoverageNode`: a declaration detail, the details its range holds, and the
/// declarations nested in it.
#[derive(Clone, Debug, PartialEq)]
pub struct DeclarationNode {
pub detail: usize,
contained: Vec<usize>,
pub children: Vec<DeclarationNode>,
}
impl DeclarationNode {
/// `attributableCoverage`: the statements and branches inside a hit declaration with a range.
pub fn attributable(&self, details: &[CoverageDetail]) -> Option<(CoverageCount, CoverageCount)> {
let own = &details[self.detail];
if own.position || !own.count.is_hit() {
return None;
}
let (mut statement, mut branch) = (CoverageCount::default(), CoverageCount::default());
for &index in &self.contained {
let detail = &details[index];
if detail.kind != DetailType::Statement {
continue;
}
statement.covered += detail.count.is_hit() as u64;
statement.total += 1;
for coverage in &detail.branches {
branch.covered += coverage.count.is_hit() as u64;
branch.total += 1;
}
}
Some((statement, branch))
}
}
/// testCoverageView.ts `updateWithDetails`: each declaration under the first one at each level that holds it.
pub fn declaration_tree(details: &[CoverageDetail]) -> Vec<DeclarationNode> {
let mut roots: Vec<DeclarationNode> = Vec::new();
for (index, detail) in details.iter().enumerate() {
if detail.kind != DetailType::Declaration {
continue;
}
let mut level = &mut roots;
while let Some(parent) = level.iter().position(|parent| parent.contained.contains(&index)) {
level = &mut level[parent].children;
}
let contained = (0..details.len()).filter(|&other| detail.contains(&details[other])).collect();
level.push(DeclarationNode { detail: index, contained, children: Vec::new() });
}
roots
}
/// codeCoverageDecorations.ts `DetailRange`: a detail (`branch` set for one of a statement's branches) over a range
/// no other range overlaps; `primary` on the range's first piece.
#[derive(Clone, Debug, PartialEq)]
pub struct DetailRange {
pub range: CoverageRange,
pub primary: bool,
pub detail: usize,
pub branch: Option<usize>,
}
impl DetailRange {
/// codeCoverageDecorations.ts `apply`'s `CLASS_HIT` or `CLASS_MISS`: a branch's count, else a statement's. A
/// declaration's range has no decoration.
pub fn hit(&self, details: &[CoverageDetail]) -> Option<bool> {
let detail = &details[self.detail];
match self.branch {
Some(branch) => Some(detail.branches[branch].count.is_hit()),
None => (detail.kind == DetailType::Statement).then(|| detail.count.is_hit()),
}
}
}
/// `CoverageDetailsModel`'s ranges: nested details split into sequential, non-overlapping ranges.
pub fn detail_ranges(details: &[CoverageDetail]) -> Vec<DetailRange> {
let mut ranges: Vec<(DetailRange, DetailType)> = details.iter().enumerate().map(|(index, detail)| (DetailRange { range: detail.location, primary: true, detail: index, branch: None }, detail.kind)).collect();
for (index, detail) in details.iter().enumerate() {
if detail.kind != DetailType::Statement {
continue;
}
for (branch, coverage) in detail.branches.iter().enumerate() {
let end = detail.location.end;
let range = coverage.location.unwrap_or(CoverageRange::new(end, end));
ranges.push((DetailRange { range, primary: true, detail: index, branch: Some(branch) }, DetailType::Branch));
}
}
// Declarations first on a tie, so single-statement functions (`() => foo()`) get inline decorations.
ranges.sort_by(|(a, a_kind), (b, b_kind)| (a.range.start, a.range.end, a_kind).cmp(&(b.range.start, b.range.end, b_kind)));
let mut stack: Vec<DetailRange> = Vec::new();
let mut result = Vec::new();
let pop = |stack: &mut Vec<DetailRange>, result: &mut Vec<DetailRange>| {
let next = stack.pop().expect("popped while not empty");
if let Some(previous) = stack.last_mut() {
previous.range = CoverageRange::new(next.range.end, previous.range.end);
}
result.push(next);
};
for (item, _) in ranges {
let start = item.range.start;
while stack.last().is_some_and(|top| !top.range.contains(start)) {
pop(&mut stack, &mut result);
}
if item.range.is_empty() {
result.push(item);
continue;
}
if let Some(previous) = stack.last_mut() {
let primary = previous.primary;
let before = CoverageRange::new(previous.range.start, start);
previous.range = CoverageRange::new(item.range.end, previous.range.end);
previous.primary = false;
let piece = DetailRange { range: before, primary, detail: previous.detail, branch: previous.branch };
if previous.range.is_empty() {
stack.pop();
}
result.push(piece);
}
stack.push(item);
}
while !stack.is_empty() {
pop(&mut stack, &mut result);
}
result
}
/// codeCoverageDecorations.ts `apply`'s inline options of one statement or branch range (`applyHoverOptions`), in
/// 0-based model positions (`validateRange`): the `coverage-deco-inline` fill unless it is a missed branch's
/// indicator, and the `countBadge` before it. `detail` and `branch` describe it for the hover.
#[derive(Clone, Debug, PartialEq)]
pub struct InlineCoverage {
pub start: (usize, usize),
pub end: (usize, usize),
pub hit: bool,
/// `coverage-deco-branch-miss-indicator`: a missed branch with an empty range in a statement that ran.
pub branch_miss: bool,
pub count: Option<String>,
pub detail: usize,
pub branch: Option<usize>,
}
pub fn inline_coverage(details: &[CoverageDetail], lines: &[String]) -> Vec<InlineCoverage> {
let mut inline = Vec::new();
for range in detail_ranges(details) {
let Some(hit) = range.hit(details) else { continue };
let detail = &details[range.detail];
let (count, branch_miss) = match range.branch {
// A condition that never ran shows no miss indicator.
Some(branch) => (detail.branches[branch].count, !hit && range.range.is_empty() && detail.branches.iter().any(|branch| branch.count.is_hit())),
None => (detail.count, false),
};
let count = match count {
HitCount::Times(times) if range.primary && times > 0 && !branch_miss => Some(if times > 99 { "99+x".to_owned() } else { format!("{times}x") }),
_ => None,
};
let (start, end) = (model_position(lines, range.range.start), model_position(lines, range.range.end));
inline.push(InlineCoverage { start, end, hit, branch_miss, count, detail: range.detail, branch: range.branch });
}
inline
}
/// `CoverageDetailsModel.describe` of a statement or one of its branches, as markdown.
pub fn describe(details: &[CoverageDetail], detail: usize, branch: Option<usize>, lines: &[String]) -> String {
let detail = &details[detail];
let text = text_in_range(lines, detail.location);
let text = wrap_name(if text.trim().is_empty() { "<empty statement>" } else { text.trim() });
if let Some(branch) = branch {
let branch_detail = &detail.branches[branch];
let label = branch_detail.label.as_deref().map_or(format!("#{}", branch + 1), wrap_in_backticks);
return match branch_detail.count {
HitCount::Times(0) | HitCount::Ran(false) => format!("Branch {label} in {text} was not covered."),
HitCount::Ran(true) => format!("Branch {label} in {text} was executed."),
HitCount::Times(times) => format!("Branch {label} in {text} was executed {times} time(s)."),
};
}
if !detail.branches.is_empty() {
let covered = detail.branches.iter().filter(|branch| branch.count.is_hit()).count();
return format!("{covered} of {} of branches in {text} were covered.", detail.branches.len());
}
// `namedDetailLabel` around the already wrapped name: upstream's double backticks.
match detail.count {
HitCount::Times(0) | HitCount::Ran(false) => format!("`{text}` was not executed."),
HitCount::Times(times) => format!("`{text}` was executed {times} time(s)."),
HitCount::Ran(true) => format!("`{text}` was executed."),
}
}
/// `validatePosition`: a 1-based position clamped to the model, as a 0-based line and column.
fn model_position(lines: &[String], position: CoveragePosition) -> (usize, usize) {
let line = (position.line as usize).max(1);
if line > lines.len() {
return (lines.len() - 1, lines[lines.len() - 1].chars().count());
}
let length = lines[line - 1].chars().count();
(line - 1, (position.column as usize).clamp(1, length + 1) - 1)
}
/// `getValueInRange`, lines joined with `\n`.
fn text_in_range(lines: &[String], range: CoverageRange) -> String {
let (start, end) = (model_position(lines, range.start), model_position(lines, range.end));
let mut text = String::new();
for line in start.0..=end.0 {
let chars = lines[line].chars();
let from = if line == start.0 { start.1 } else { 0 };
let to = if line == end.0 { end.1 } else { usize::MAX };
text.extend(chars.skip(from).take(to.saturating_sub(from)));
if line < end.0 {
text.push('\n');
}
}
text
}
fn wrap_in_backticks(text: &str) -> String {
format!("`{}`", text.replace(['\n', '\r', '`'], ""))
}
fn wrap_name(name: &str) -> String {
match name.chars().count() > 50 {
true => wrap_in_backticks(&format!("{}...", name.chars().take(40).collect::<String>())),
false => wrap_in_backticks(name),
}
}