-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Using `clang-format`. Needs support for specifying settings, but that should come in its own PR.
- Loading branch information
Showing
4 changed files
with
59 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
pub trait Format { | ||
fn format(&self, src: &std::path::Path) -> anyhow::Result<()>; | ||
} | ||
|
||
pub struct ClangFormat; | ||
|
||
impl Format for ClangFormat { | ||
fn format(&self, src: &std::path::Path) -> anyhow::Result<()> { | ||
let paths = walkdir::WalkDir::new(src) | ||
.into_iter() | ||
.flat_map(std::convert::identity) // Filter out walkdir failures | ||
.filter(|e| e.path().extension().filter(|ext| *ext == "c" || *ext == "h").is_some()) // Only formatting .c and .h files | ||
.map(|e| e.path().to_owned()); // Retrieving paths of files | ||
|
||
let cmd = std::process::Command::new("clang-format") | ||
.args(paths) | ||
.arg("-i") // Format in place (edit files) | ||
.output()?; | ||
|
||
if cmd.status.success() { | ||
Ok(()) | ||
} else { | ||
Err(anyhow::anyhow!("Failed to format files. {}", String::from_utf8_lossy(&cmd.stderr))) | ||
} | ||
} | ||
} | ||
|
||
/// Tries to find an available C formatter | ||
/// Currently only supports clang-format. | ||
pub fn try_locate() -> anyhow::Result<Box<dyn Format>> { | ||
match which::which("clang-format") { | ||
Ok(path) => Ok(Box::new(ClangFormat)), | ||
Err(_) => Err(anyhow::anyhow!("Couldn't find clang-format.")) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters