use super::*;
#[inline]
pub fn detect_format_kind(path: &Path) -> FileFormatKind {
let Some(name) = path.file_name().and_then(OsStr::to_str) else {
return FileFormatKind::Unsupported;
};
if let Some(&first_byte) = name.as_bytes().first() {
match first_byte {
FMT_BYTE_DOT => {
if FMT_NAME_YAML.contains(&name) {
return FileFormatKind::Yaml;
}
if FMT_NAME_PRESERVE_TABS.contains(&name) {
return FileFormatKind::PlainTextPreserveTabs;
}
if FMT_NAME_PLAIN_TEXT.contains(&name) || name.starts_with(FMT_PREFIX_DOTENV) {
return FileFormatKind::PlainText;
}
}
FMT_BYTE_UPPER_D => {
if FMT_NAME_PLAIN_TEXT.contains(&name) || name.starts_with(FMT_PREFIX_DOCKERFILE) {
return FileFormatKind::PlainText;
}
}
FMT_BYTE_UPPER_L => {
if FMT_NAME_PLAIN_TEXT.contains(&name) {
return FileFormatKind::PlainText;
}
}
FMT_BYTE_UPPER_M | FMT_BYTE_LOWER_M => {
if FMT_NAME_PRESERVE_TABS.contains(&name) {
return FileFormatKind::PlainTextPreserveTabs;
}
}
FMT_BYTE_LOWER_C | FMT_BYTE_LOWER_P => {
if FMT_NAME_JSON_STRINGIFY.contains(&name) {
return FileFormatKind::JsonStringify;
}
if FMT_NAME_PLAIN_TEXT.contains(&name) {
return FileFormatKind::PlainText;
}
}
_ => {}
}
}
let raw_ext: &str = match name.rsplit_once('.') {
Some((stem, ext)) if !stem.is_empty() => ext,
_ => return FileFormatKind::Unsupported,
};
let ext_bytes: &[u8] = raw_ext.as_bytes();
if ext_bytes.is_empty() || ext_bytes.len() > FMT_EXT_MAX_LEN {
return FileFormatKind::Unsupported;
}
let mut stack_buf: [u8; FMT_EXT_MAX_LEN] = [0u8; FMT_EXT_MAX_LEN];
let ext_len: usize = ext_bytes.len();
for (dst, &src) in stack_buf[..ext_len].iter_mut().zip(ext_bytes.iter()) {
*dst = src.to_ascii_lowercase();
}
let ext: &str = match from_utf8(&stack_buf[..ext_len]) {
Ok(s) => s,
Err(_) => return FileFormatKind::Unsupported,
};
match stack_buf[0] {
FMT_BYTE_LOWER_R if ext == FMT_EXT_RUST => FileFormatKind::Rust,
FMT_BYTE_LOWER_M => {
if FMT_EXT_MARKDOWN.contains(&ext) {
FileFormatKind::Markdown
} else if FMT_EXT_JAVASCRIPT.contains(&ext) {
FileFormatKind::JavaScript
} else if FMT_EXT_TYPESCRIPT.contains(&ext) {
FileFormatKind::TypeScript
} else if FMT_EXT_PLAIN_TEXT.contains(&ext) {
FileFormatKind::PlainText
} else {
FileFormatKind::Unsupported
}
}
FMT_BYTE_LOWER_T => {
if FMT_EXT_TOML.contains(&ext) {
FileFormatKind::Toml
} else if FMT_EXT_TYPESCRIPT.contains(&ext) {
FileFormatKind::TypeScript
} else if FMT_EXT_TSX.contains(&ext) {
FileFormatKind::TypeScriptReact
} else if FMT_EXT_PLAIN_TEXT.contains(&ext) {
FileFormatKind::PlainText
} else {
FileFormatKind::Unsupported
}
}
FMT_BYTE_LOWER_Y if FMT_EXT_YAML.contains(&ext) => FileFormatKind::Yaml,
FMT_BYTE_LOWER_J => {
if FMT_EXT_JSON.contains(&ext) {
FileFormatKind::Json
} else if FMT_EXT_JSONC.contains(&ext) {
FileFormatKind::Jsonc
} else if FMT_EXT_JAVASCRIPT.contains(&ext) {
FileFormatKind::JavaScript
} else {
FileFormatKind::Unsupported
}
}
FMT_BYTE_LOWER_C => {
if FMT_EXT_CSS.contains(&ext) {
FileFormatKind::Css
} else if FMT_EXT_JAVASCRIPT.contains(&ext) {
FileFormatKind::JavaScript
} else if FMT_EXT_TYPESCRIPT.contains(&ext) {
FileFormatKind::TypeScript
} else if FMT_EXT_JSONC.contains(&ext) {
FileFormatKind::Jsonc
} else if FMT_EXT_PLAIN_TEXT.contains(&ext) {
FileFormatKind::PlainText
} else {
FileFormatKind::Unsupported
}
}
FMT_BYTE_LOWER_S => {
if FMT_EXT_SCSS.contains(&ext) {
FileFormatKind::Scss
} else if FMT_EXT_PLAIN_TEXT.contains(&ext) {
FileFormatKind::PlainText
} else {
FileFormatKind::Unsupported
}
}
FMT_BYTE_LOWER_L if FMT_EXT_LESS.contains(&ext) => FileFormatKind::Less,
FMT_BYTE_LOWER_H if FMT_EXT_HTML.contains(&ext) => FileFormatKind::Html,
FMT_BYTE_LOWER_V if FMT_EXT_VUE.contains(&ext) => FileFormatKind::Vue,
FMT_BYTE_LOWER_W => {
if FMT_EXT_JAVASCRIPT.contains(&ext) {
FileFormatKind::JavaScript
} else if FMT_EXT_CSS.contains(&ext) {
FileFormatKind::Css
} else {
FileFormatKind::Unsupported
}
}
_ => {
if FMT_PLAIN_TEXT_ONLY_FIRST_BYTES.contains(&stack_buf[0])
&& FMT_EXT_PLAIN_TEXT.contains(&ext)
{
FileFormatKind::PlainText
} else {
FileFormatKind::Unsupported
}
}
}
}
pub fn format_text_by_path(path: &Path, input: &str) -> String {
match detect_format_kind(path) {
FileFormatKind::Markdown => format_markdown(input),
FileFormatKind::Yaml => format_yaml_with_path(input, path),
FileFormatKind::Json => format_json(input).unwrap_or_else(|_: io::Error| input.to_string()),
FileFormatKind::JsonStringify => {
format_json_stringify(input).unwrap_or_else(|_: io::Error| input.to_string())
}
FileFormatKind::Jsonc => format_jsonc(input),
FileFormatKind::Toml => format_toml(input),
FileFormatKind::JavaScript => format_javascript_with_path(input, path),
FileFormatKind::TypeScript => format_typescript_with_path(input, path),
FileFormatKind::TypeScriptReact => format_tsx_with_path(input, path),
FileFormatKind::Css => format_css(input),
FileFormatKind::Scss => format_scss(input),
FileFormatKind::Less => format_less(input),
FileFormatKind::Html => format_html_with_path(input, path),
FileFormatKind::Vue => format_vue_with_path(input, path),
FileFormatKind::PlainText
| FileFormatKind::PlainTextPreserveTabs
| FileFormatKind::Rust
| FileFormatKind::Unsupported => input.to_string(),
}
}
fn format_single_text_file(file_path: &Path, check: bool) -> Result<Option<String>, io::Error> {
let original: String = match fs::read_to_string(file_path) {
Ok(text) => text,
Err(_) => return Ok(None),
};
let formatted: String = format_text_by_path(file_path, &original);
if formatted != original {
if !check {
fs::write(file_path, formatted)?;
}
return Ok(Some(file_path.display().to_string()));
}
Ok(None)
}
pub fn format_workspace_text_files(
root: &Path,
check: bool,
) -> Result<UnifiedFmtReport, io::Error> {
let ignore_rules: Vec<PrettierIgnoreRule> = if root.is_dir() {
load_prettier_ignore(root)
} else {
Vec::new()
};
let mut files: Vec<PathBuf> = Vec::new();
collect_text_files(root, root, &ignore_rules, &mut files)?;
files.sort();
let total_files: usize = files.len();
let worker_count: usize = if total_files < FMT_PARALLEL_THRESHOLD {
1
} else {
let scaled: usize = (total_files / FMT_FILES_PER_WORKER).max(1);
available_parallelism()
.map(|n: NonZeroUsize| n.get())
.unwrap_or(1)
.min(scaled)
.min(total_files)
};
let mut changed_files: Vec<String> = Vec::new();
if worker_count <= 1 {
for file_path in &files {
if let Some(changed) = format_single_text_file(file_path, check)? {
changed_files.push(changed);
}
}
} else {
let next_idx: AtomicUsize = AtomicUsize::new(0);
let worker_results: Vec<Vec<IndexedFmtOutcome>> = scope(|s: &Scope<'_, '_>| {
let mut handles: Vec<ScopedJoinHandle<'_, Vec<IndexedFmtOutcome>>> =
Vec::with_capacity(worker_count);
for _ in 0..worker_count {
let files_ref: &[PathBuf] = &files;
let next_ref: &AtomicUsize = &next_idx;
handles.push(s.spawn(move || {
let mut local: Vec<IndexedFmtOutcome> = Vec::new();
loop {
let idx: usize = next_ref.fetch_add(1, Ordering::Relaxed);
if idx >= files_ref.len() {
break;
}
let res: Result<Option<String>, io::Error> =
format_single_text_file(&files_ref[idx], check);
if !matches!(res, Ok(None)) {
local.push((idx, res));
}
}
local
}));
}
let mut collected: Vec<Vec<IndexedFmtOutcome>> = Vec::with_capacity(worker_count);
for handle in handles {
if let Ok(part) = handle.join() {
collected.push(part);
}
}
collected
});
let mut merged: Vec<IndexedFmtOutcome> = Vec::new();
for part in worker_results {
merged.extend(part);
}
merged.sort_by_key(|(idx, _): &IndexedFmtOutcome| *idx);
for (_, res) in merged {
if let Some(changed) = res? {
changed_files.push(changed);
}
}
}
let formatted_count: usize = changed_files.len();
let report: UnifiedFmtReport =
UnifiedFmtReport::new(total_files, formatted_count, check, changed_files);
if check && report.get_files_formatted() > 0 {
return Err(io::Error::other(format!(
"{ERROR_TEXT_FMT_CHECK_FAILED}: {}",
report.get_changed_files().join(", ")
)));
}
Ok(report)
}
pub async fn execute_unified_fmt(root: &Path, check: bool) -> Result<UnifiedFmtReport, io::Error> {
let (workspace_root, manifest_path): (PathBuf, PathBuf) = if root.is_file() {
let parent: PathBuf = root
.parent()
.filter(|p: &&Path| !p.as_os_str().is_empty())
.map(Path::to_path_buf)
.unwrap_or_else(|| PathBuf::from("."));
(parent, root.to_path_buf())
} else {
(root.to_path_buf(), root.join(CARGO_TOML))
};
let report: UnifiedFmtReport = format_workspace_text_files(&workspace_root, check)?;
if manifest_path.exists() {
let manifest_str: String = manifest_path.display().to_string();
if !check {
format_derive_attributes(&manifest_str).await?;
}
run_cargo_fmt(Some(&manifest_str), check).await?;
}
Ok(report)
}
#[inline(always)]
fn is_active_text_format(kind: FileFormatKind) -> bool {
!matches!(
kind,
FileFormatKind::Rust
| FileFormatKind::PlainText
| FileFormatKind::PlainTextPreserveTabs
| FileFormatKind::Unsupported
)
}
fn collect_text_files(
root: &Path,
path: &Path,
ignore_rules: &[PrettierIgnoreRule],
out: &mut Vec<PathBuf>,
) -> Result<(), io::Error> {
if path.is_file() {
let kind: FileFormatKind = detect_format_kind(path);
if is_active_text_format(kind) {
out.push(path.to_path_buf());
}
return Ok(());
}
if !path.is_dir() {
return Ok(());
}
collect_text_files_in_dir(root, path, ignore_rules, out)
}
fn collect_text_files_in_dir(
root: &Path,
dir: &Path,
ignore_rules: &[PrettierIgnoreRule],
out: &mut Vec<PathBuf>,
) -> Result<(), io::Error> {
let has_ignore: bool = !ignore_rules.is_empty();
for entry_res in fs::read_dir(dir)? {
let entry: DirEntry = entry_res?;
let file_type: FileType = entry.file_type()?;
if file_type.is_symlink() {
continue;
}
if file_type.is_dir() {
let name_os: OsString = entry.file_name();
if let Some(name) = name_os.to_str()
&& FMT_SKIP_DIRS.contains(&name)
{
continue;
}
let child: PathBuf = entry.path();
if has_ignore {
let rel_posix: Cow<'_, str> = to_relative_posix(root, &child);
if is_prettier_ignored(&rel_posix, true, ignore_rules) {
continue;
}
}
collect_text_files_in_dir(root, &child, ignore_rules, out)?;
} else if file_type.is_file() {
let child: PathBuf = entry.path();
let kind: FileFormatKind = detect_format_kind(&child);
if !is_active_text_format(kind) {
continue;
}
if has_ignore {
let rel_posix: Cow<'_, str> = to_relative_posix(root, &child);
if is_prettier_ignored(&rel_posix, false, ignore_rules) {
continue;
}
}
out.push(child);
}
}
Ok(())
}
fn load_prettier_ignore(root: &Path) -> Vec<PrettierIgnoreRule> {
let ignore_path: PathBuf = root.join(FMT_PRETTIER_IGNORE_FILE);
let content: String = match fs::read_to_string(&ignore_path) {
Ok(text) => text,
Err(_) => return Vec::new(),
};
let mut rules: Vec<PrettierIgnoreRule> = Vec::new();
for raw_line in normalize_line_endings(&content).split(TEXT_LF) {
let trimmed: &str = raw_line.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
let (negated, after_bang): (bool, &str) = match trimmed.strip_prefix('!') {
Some(rest) => (true, rest),
None => (false, trimmed),
};
let (dir_only, after_slash): (bool, &str) = match after_bang.strip_suffix('/') {
Some(rest) => (true, rest),
None => (false, after_bang),
};
let (leading_slash, body): (bool, &str) = match after_slash.strip_prefix('/') {
Some(rest) => (true, rest),
None => (false, after_slash),
};
if body.is_empty() {
continue;
}
let anchored: bool = leading_slash || body.contains('/');
rules.push(PrettierIgnoreRule::new(
body.to_string(),
negated,
dir_only,
anchored,
));
}
rules
}
#[inline(always)]
fn to_relative_posix<'a>(root: &Path, child: &'a Path) -> Cow<'a, str> {
let rel: &'a Path = child.strip_prefix(root).unwrap_or(child);
let lossy: Cow<'a, str> = rel.to_string_lossy();
if lossy.contains('\\') {
Cow::Owned(lossy.replace('\\', "/"))
} else {
lossy
}
}
fn is_prettier_ignored(rel_path: &str, is_dir: bool, rules: &[PrettierIgnoreRule]) -> bool {
if rules.is_empty() || rel_path.is_empty() {
return false;
}
let mut ignored: bool = false;
for rule in rules {
if rule_matches_path(rule, rel_path, is_dir) {
ignored = !rule.get_negated();
}
}
ignored
}
fn rule_matches_path(rule: &PrettierIgnoreRule, rel_path: &str, is_dir: bool) -> bool {
let pattern: &str = rule.get_pattern();
let anchored: bool = rule.get_anchored();
if rule.get_negated() {
if rule.get_dir_only() && !is_dir {
return false;
}
return match_pattern_against(pattern, anchored, rel_path);
}
if (!rule.get_dir_only() || is_dir) && match_pattern_against(pattern, anchored, rel_path) {
return true;
}
let mut cursor: usize = 0;
while let Some(pos) = rel_path[cursor..].find('/') {
let dir_prefix: &str = &rel_path[..(cursor + pos)];
if match_pattern_against(pattern, anchored, dir_prefix) {
return true;
}
cursor += pos + 1;
}
false
}
#[inline(always)]
fn match_pattern_against(pattern: &str, anchored: bool, rel_path: &str) -> bool {
if anchored {
return glob_match_path(pattern.as_bytes(), rel_path.as_bytes());
}
let base: &str = rel_path.rsplit('/').next().unwrap_or(rel_path);
glob_match_path(pattern.as_bytes(), base.as_bytes())
}
fn glob_match_dp(pat: &[u8], text: &[u8], prev: &mut [bool], curr: &mut [bool]) -> bool {
let plen: usize = pat.len();
let tlen: usize = text.len();
prev[0] = true;
let mut pi: usize = 0;
let mut use_prev: bool = true;
while pi < plen {
let (src, dst): (&[bool], &mut [bool]) = if use_prev {
(&prev[..=tlen], &mut curr[..=tlen])
} else {
(&curr[..=tlen], &mut prev[..=tlen])
};
dst.fill(false);
if (pi == 0 || pat[pi - 1] == FMT_GLOB_SLASH)
&& pi + 2 < plen
&& pat[pi] == FMT_GLOB_STAR
&& pat[pi + 1] == FMT_GLOB_STAR
&& pat[pi + 2] == FMT_GLOB_SLASH
{
let mut seen: bool = false;
for ti in 0..=tlen {
if src[ti] {
dst[ti] = true;
seen = true;
}
if seen && ti < tlen && text[ti] == FMT_GLOB_SLASH {
dst[ti + 1] = true;
}
}
pi += 3;
} else if pat[pi] == FMT_GLOB_STAR && pi + 1 < plen && pat[pi + 1] == FMT_GLOB_STAR {
let mut seen: bool = false;
for ti in 0..=tlen {
if src[ti] {
seen = true;
}
dst[ti] = seen;
}
pi += 2;
} else if pat[pi] == FMT_GLOB_STAR {
for ti in 0..=tlen {
if src[ti] || (ti > 0 && dst[ti - 1] && text[ti - 1] != FMT_GLOB_SLASH) {
dst[ti] = true;
}
}
pi += 1;
} else if pat[pi] == FMT_GLOB_QUESTION {
for ti in 1..=tlen {
if src[ti - 1] && text[ti - 1] != FMT_GLOB_SLASH {
dst[ti] = true;
}
}
pi += 1;
} else {
let expected: u8 = pat[pi];
for ti in 1..=tlen {
if src[ti - 1] && text[ti - 1] == expected {
dst[ti] = true;
}
}
pi += 1;
}
use_prev = !use_prev;
}
if use_prev { prev[tlen] } else { curr[tlen] }
}
fn glob_match_path(pat: &[u8], text: &[u8]) -> bool {
if !pat.contains(&FMT_GLOB_STAR) && !pat.contains(&FMT_GLOB_QUESTION) {
return pat == text;
}
let tlen: usize = text.len();
if tlen < FMT_GLOB_STACK_CAP {
let mut prev: [bool; FMT_GLOB_STACK_CAP] = [false; FMT_GLOB_STACK_CAP];
let mut curr: [bool; FMT_GLOB_STACK_CAP] = [false; FMT_GLOB_STACK_CAP];
return glob_match_dp(pat, text, &mut prev[..=tlen], &mut curr[..=tlen]);
}
let mut prev: Vec<bool> = vec![false; tlen + 1];
let mut curr: Vec<bool> = vec![false; tlen + 1];
glob_match_dp(pat, text, &mut prev, &mut curr)
}
#[inline(always)]
fn cmp_trait_lowercase(a: &str, b: &str) -> cmp::Ordering {
if a.is_ascii() && b.is_ascii() {
let ab: &[u8] = a.as_bytes();
let bb: &[u8] = b.as_bytes();
let min_len: usize = ab.len().min(bb.len());
for i in 0..min_len {
let ord: cmp::Ordering = ab[i].to_ascii_lowercase().cmp(&bb[i].to_ascii_lowercase());
if ord != cmp::Ordering::Equal {
return ord;
}
}
return ab.len().cmp(&bb.len());
}
a.chars()
.flat_map(char::to_lowercase)
.cmp(b.chars().flat_map(char::to_lowercase))
}
fn sort_derive_in_line(line: &str) -> Option<String> {
let captures: Captures<'_> = DERIVE_REGEX.captures(line)?;
let content_match: Match<'_> = captures.get(1)?;
let derive_content: &str = content_match.as_str();
let mut traits: Vec<&str> = derive_content
.split(',')
.map(str::trim)
.filter(|s: &&str| !s.is_empty())
.collect();
traits.sort_by(|a: &&str, b: &&str| cmp_trait_lowercase(a, b));
let mut sorted_traits: String = String::with_capacity(derive_content.len());
for (idx, tr) in traits.iter().enumerate() {
if idx > 0 {
sorted_traits.push_str(", ");
}
sorted_traits.push_str(tr);
}
if sorted_traits == derive_content {
return None;
}
let mut result: String = String::with_capacity(line.len() + sorted_traits.len());
result.push_str(&line[..content_match.start()]);
result.push_str(&sorted_traits);
result.push_str(&line[content_match.end()..]);
Some(result)
}
async fn format_derive_in_file(file_path: &Path) -> Result<bool, io::Error> {
let content: String = read_to_string(file_path).await?;
if !content.contains(DERIVE_PREFIX) {
return Ok(false);
}
let mut modified: bool = false;
let mut new_content: Option<String> = None;
let mut seen_lines: Vec<&str> = Vec::new();
for line in content.lines() {
let trimmed: &str = line.trim();
if trimmed.starts_with(DERIVE_PREFIX)
&& let Some(sorted) = sort_derive_in_line(line)
{
modified = true;
let buf: &mut String = new_content.get_or_insert_with(|| {
let mut s: String = String::with_capacity(content.len() + 16);
for prev in &seen_lines {
s.push_str(prev);
s.push(TEXT_LF);
}
s
});
buf.push_str(&sorted);
buf.push(TEXT_LF);
continue;
}
if let Some(ref mut buf) = new_content {
buf.push_str(line);
buf.push(TEXT_LF);
} else {
seen_lines.push(line);
}
}
if modified && let Some(updated) = new_content {
write(file_path, updated).await?;
}
Ok(modified)
}
async fn find_rust_files(manifest_path: &Path) -> Result<Vec<PathBuf>, io::Error> {
let mut files: Vec<PathBuf> = Vec::new();
let workspace_root: &Path = manifest_path.parent().unwrap_or(Path::new("."));
let src_dir: PathBuf = workspace_root.join("src");
if src_dir.exists() {
find_rust_files_in_dir(&src_dir, &mut files).await?;
}
let content: String = read_to_string(manifest_path).await?;
if let Ok(doc) = from_str::<Value>(&content)
&& let Some(workspace) = doc.get(TOML_WORKSPACE)
&& let Some(members) = workspace
.get(TOML_MEMBERS)
.and_then(|m: &Value| m.as_array())
{
for member in members {
if let Some(pattern) = member.as_str() {
let member_src: PathBuf = workspace_root.join(pattern).join("src");
if member_src.exists() {
find_rust_files_in_dir(&member_src, &mut files).await?;
}
}
}
}
Ok(files)
}
async fn find_rust_files_in_dir(dir: &Path, files: &mut Vec<PathBuf>) -> Result<(), io::Error> {
let mut entries: ReadDir = read_dir(dir).await?;
while let Some(entry) = entries.next_entry().await? {
let file_type: FileType = entry.file_type().await?;
let path: PathBuf = entry.path();
if file_type.is_file()
&& path
.extension()
.is_some_and(|ext: &OsStr| ext == FMT_EXT_RUST)
{
files.push(path);
} else if file_type.is_dir() {
Box::pin(find_rust_files_in_dir(&path, files)).await?;
}
}
Ok(())
}
async fn format_derive_attributes(manifest_path: &str) -> Result<(), io::Error> {
let path: &Path = Path::new(manifest_path);
let files: Vec<PathBuf> = find_rust_files(path).await?;
let modified_count: Arc<AtomicUsize> = Arc::new(AtomicUsize::new(0));
let mut handles: Vec<JoinHandle<Result<(), io::Error>>> = Vec::with_capacity(files.len());
for file in files {
let counter: Arc<AtomicUsize> = Arc::clone(&modified_count);
let handle: JoinHandle<Result<(), io::Error>> = spawn(async move {
if format_derive_in_file(&file).await? {
counter.fetch_add(1, Ordering::Relaxed);
}
Ok(())
});
handles.push(handle);
}
for handle in handles {
handle.await??;
}
let count: usize = modified_count.load(Ordering::Relaxed);
if count > 0 {
log::info!("Sorted derive attributes in {count} files");
}
Ok(())
}
async fn run_cargo_fmt(manifest_path: Option<&str>, check: bool) -> Result<(), io::Error> {
let mut cmd: Command = Command::new(CARGO);
cmd.arg(CARGO_FMT);
if check {
cmd.arg(CLI_FLAG_CHECK);
}
if let Some(manifest) = manifest_path {
cmd.arg(CLI_FLAG_MANIFEST_PATH).arg(manifest);
}
cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
let output: Output = cmd.output().await?;
let stdout: String = String::from_utf8_lossy(&output.stdout).trim().to_string();
let stderr: String = String::from_utf8_lossy(&output.stderr).trim().to_string();
if !stdout.is_empty() {
for line in stdout.lines() {
log::info!("{line}");
}
}
if !stderr.is_empty() {
if output.status.success() {
for line in stderr.lines() {
if line.is_empty() {
continue;
}
log::info!("{line}");
}
} else {
for line in stderr.lines() {
if line.is_empty() {
continue;
}
log::error!("{line}");
}
}
}
if !output.status.success() {
return Err(io::Error::other(ERROR_FMT_FAILED));
}
Ok(())
}
fn is_cargo_clippy_installed() -> bool {
which(CARGO_CLIPPY).is_ok()
}
async fn install_cargo_clippy() -> Result<(), io::Error> {
log::warn!("cargo-clippy not found, installing...");
let output: Output = Command::new(RUSTUP)
.arg(RUSTUP_COMPONENT)
.arg("add")
.arg(CLIPPY)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
.await?;
let stdout: String = String::from_utf8_lossy(&output.stdout).trim().to_string();
let stderr: String = String::from_utf8_lossy(&output.stderr).trim().to_string();
if !stdout.is_empty() {
for line in stdout.lines() {
log::info!("{line}");
}
}
if !stderr.is_empty() {
if output.status.success() {
for line in stderr.lines() {
if line.is_empty() {
continue;
}
log::info!("{line}");
}
} else {
for line in stderr.lines() {
if line.is_empty() {
continue;
}
log::error!("{line}");
}
}
}
if !output.status.success() {
return Err(io::Error::other(ERROR_CLIPPY_INSTALL_FAILED));
}
Ok(())
}
async fn execute_clippy_fix(args: &Args) -> Result<(), io::Error> {
if !is_cargo_clippy_installed() {
install_cargo_clippy().await?;
}
let mut cmd: Command = Command::new(CARGO);
cmd.arg(CLIPPY)
.arg(CLI_FLAG_FIX)
.arg(CLI_FLAG_WORKSPACE)
.arg(CLI_FLAG_ALL_TARGETS)
.arg(CLI_FLAG_ALLOW_DIRTY);
if let Some(ref manifest_path) = args.manifest_path {
cmd.arg(CLI_FLAG_MANIFEST_PATH).arg(manifest_path);
}
cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
let output: Output = cmd.output().await?;
let stdout: String = String::from_utf8_lossy(&output.stdout).trim().to_string();
let stderr: String = String::from_utf8_lossy(&output.stderr).trim().to_string();
if !stdout.is_empty() {
for line in stdout.lines() {
log::info!("{line}");
}
}
if !stderr.is_empty() {
if output.status.success() {
for line in stderr.lines() {
if line.is_empty() {
continue;
}
log::info!("{line}");
}
} else {
for line in stderr.lines() {
if line.is_empty() {
continue;
}
log::error!("{line}");
}
}
}
if !output.status.success() {
return Err(io::Error::other(ERROR_CLIPPY_FIX_FAILED));
}
Ok(())
}
pub async fn execute_fmt(args: &Args) -> Result<(), io::Error> {
let manifest_path: String = args
.manifest_path
.clone()
.unwrap_or_else(|| CARGO_TOML.to_string());
let manifest: &Path = Path::new(&manifest_path);
let workspace_root: &Path = manifest
.parent()
.filter(|p: &&Path| !p.as_os_str().is_empty())
.unwrap_or(Path::new("."));
let report: UnifiedFmtReport = format_workspace_text_files(workspace_root, args.check)?;
if report.get_files_formatted() > 0 {
log::info!(
"Formatted {} text files (scanned {})",
report.get_files_formatted(),
report.get_files_scanned()
);
}
if !args.check {
format_derive_attributes(&manifest_path).await?;
}
run_cargo_fmt(args.manifest_path.as_deref(), args.check).await?;
if !args.check {
execute_clippy_fix(args).await?;
}
Ok(())
}
pub async fn format_path(path: &Path) -> Result<(), io::Error> {
let kind: FileFormatKind = detect_format_kind(path);
if path.is_file() && kind != FileFormatKind::Rust {
if is_active_text_format(kind) {
let _: UnifiedFmtReport = format_workspace_text_files(path, false)?;
}
return Ok(());
}
if path.is_dir() {
let _: UnifiedFmtReport = format_workspace_text_files(path, false)?;
}
let mut cmd: Command = Command::new(CARGO);
cmd.arg(CARGO_FMT).arg("--").arg(path);
cmd.stdout(Stdio::null()).stderr(Stdio::null());
let _: ExitStatus = cmd.status().await?;
Ok(())
}