1use std::{fs, path::Path};23use anyhow::{bail, Result};4use xshell::{cmd, Shell};5678pub fn ensure_file_contents(file: &Path, contents: &str) -> Result<()> {9 if let Ok(old_contents) = fs::read_to_string(file) {10 if normalize_newlines(&old_contents) == normalize_newlines(contents) {11 12 return Ok(());13 }14 }1516 eprintln!(" {} was not up-to-date, updating\n", file.display());17 if std::env::var("CI").is_ok() {18 eprintln!("NOTE: run `cargo test` locally and commit the updated files\n");19 }20 if let Some(parent) = file.parent() {21 let _ = fs::create_dir_all(parent);22 }23 fs::write(file, contents).unwrap();24 bail!("some file was not up to date and has been updated, simply re-run the tests");25}262728fn normalize_newlines(s: &str) -> String {29 s.replace("\r\n", "\n")30}3132pub(crate) fn pluralize(s: &str) -> String {33 format!("{}s", s)34}3536pub fn to_upper_snake_case(s: &str) -> String {37 let mut buf = String::with_capacity(s.len());38 let mut prev = false;39 for c in s.chars() {40 if c.is_ascii_uppercase() && prev {41 buf.push('_')42 }43 prev = true;4445 buf.push(c.to_ascii_uppercase());46 }47 buf48}49pub fn to_lower_snake_case(s: &str) -> String {50 let mut buf = String::with_capacity(s.len());51 let mut prev = false;52 for c in s.chars() {53 if c.is_ascii_uppercase() && prev {54 buf.push('_')55 }56 prev = true;5758 buf.push(c.to_ascii_lowercase());59 }60 buf61}6263pub fn to_pascal_case(s: &str) -> String {64 let mut buf = String::with_capacity(s.len());65 let mut prev_is_underscore = true;66 for c in s.chars() {67 if c == '_' {68 prev_is_underscore = true;69 } else if prev_is_underscore {70 buf.push(c.to_ascii_uppercase());71 prev_is_underscore = false;72 } else {73 buf.push(c.to_ascii_lowercase());74 }75 }76 buf77}7879pub fn reformat(text: &str) -> Result<String> {80 81 82 let sh = Shell::new()?;83 let stdout = cmd!(sh, "rustfmt --config fn_single_line=true")84 .stdin(text)85 .read()?;86 Ok(format!(87 "{}\n\n{}\n",88 "//! This is a generated file, please do not edit manually. Changes can be89//! made in codegeneration that lives in `xtask` top-level dir.",90 stdout91 ))92}