Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ authors = [
description = "Run clang-format and clang-tidy on a batch of files."
homepage = "https://cpp-linter.github.io/cpp-linter-rs"
license = "MIT"
edition = "2024"

[profile.release]
lto = true
Expand Down
2 changes: 1 addition & 1 deletion bindings/node/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
[package]
name = "cpp-linter-js"
edition = "2021"
readme = "README.md"
keywords = ["clang-tidy", "clang-format", "linter"]
categories = ["command-line-utilities", "development-tools", "filesystem"]
repository = "https://github.com/cpp-linter/cpp-linter-rs"
version.workspace = true
edition.workspace = true
authors.workspace = true
description.workspace = true
homepage.workspace = true
Expand Down
2 changes: 1 addition & 1 deletion bindings/python/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
[package]
name = "cpp-linter-py"
edition = "2021"
readme = "README.md"
repository = "https://github.com/cpp-linter/cpp-linter-rs/tree/main/bindings/python"
version.workspace = true
edition.workspace = true
authors.workspace = true
description.workspace = true
homepage.workspace = true
Expand Down
2 changes: 1 addition & 1 deletion cpp-linter/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
[package]
name = "cpp-linter"
edition = "2021"
readme = "README.md"
keywords = ["clang-tidy", "clang-format", "linter"]
categories = ["command-line-utilities", "development-tools", "filesystem"]
repository = "https://github.com/cpp-linter/cpp-linter-rs"
version.workspace = true
edition.workspace = true
authors.workspace = true
description.workspace = true
homepage.workspace = true
Expand Down
12 changes: 6 additions & 6 deletions cpp-linter/src/clang_tools/clang_format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use serde::Deserialize;
use super::MakeSuggestions;
use crate::{
cli::ClangParams,
common_fs::{get_line_count_from_offset, FileObj},
common_fs::{FileObj, get_line_count_from_offset},
};

#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
Expand Down Expand Up @@ -71,10 +71,10 @@ pub fn tally_format_advice(files: &[Arc<Mutex<FileObj>>]) -> u64 {
let mut total = 0;
for file in files {
let file = file.lock().unwrap();
if let Some(advice) = &file.format_advice {
if !advice.replacements.is_empty() {
total += 1;
}
if let Some(advice) = &file.format_advice
&& !advice.replacements.is_empty()
{
total += 1;
}
}
total
Expand Down Expand Up @@ -187,7 +187,7 @@ pub fn run_clang_format(

#[cfg(test)]
mod tests {
use super::{summarize_style, FormatAdvice, Replacement};
use super::{FormatAdvice, Replacement, summarize_style};

#[test]
fn parse_blank_xml() {
Expand Down
22 changes: 10 additions & 12 deletions cpp-linter/src/clang_tools/clang_tidy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use serde::Deserialize;
use super::MakeSuggestions;
use crate::{
cli::{ClangParams, LinesChangedOnly},
common_fs::{normalize_path, FileObj},
common_fs::{FileObj, normalize_path},
};

/// Used to deserialize a json compilation database's translation unit.
Expand Down Expand Up @@ -205,21 +205,19 @@ fn parse_tidy_output(
found_fix = false;
} else if let Some(capture) = fixed_note.captures(line) {
let fixed_line = capture[1].parse()?;
if let Some(note) = &mut notification {
if !note.fixed_lines.contains(&fixed_line) {
note.fixed_lines.push(fixed_line);
}
if let Some(note) = &mut notification
&& !note.fixed_lines.contains(&fixed_line)
{
note.fixed_lines.push(fixed_line);
}
// Suspend capturing subsequent lines as suggestions until
// a new notification is constructed. If we found a note about applied fixes,
// then the lines of suggestions for that notification have already been parsed.
found_fix = true;
} else if !found_fix {
if let Some(note) = &mut notification {
// append lines of code that are part of
// the previous line's notification
note.suggestion.push(line.to_string());
}
} else if !found_fix && let Some(note) = &mut notification {
// append lines of code that are part of
// the previous line's notification
note.suggestion.push(line.to_string());
}
}
if let Some(note) = notification {
Expand Down Expand Up @@ -358,7 +356,7 @@ mod test {
common_fs::FileObj,
};

use super::{run_clang_tidy, TidyNotification, NOTE_HEADER};
use super::{NOTE_HEADER, TidyNotification, run_clang_tidy};

#[test]
fn clang_diagnostic_link() {
Expand Down
61 changes: 32 additions & 29 deletions cpp-linter/src/clang_tools/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use std::{
};

// non-std crates
use anyhow::{anyhow, Context, Result};
use anyhow::{Context, Result, anyhow};
use git2::{DiffOptions, Patch};
use regex::Regex;
use semver::Version;
Expand All @@ -22,12 +22,12 @@ use which::{which, which_in};
use super::common_fs::FileObj;
use crate::{
cli::{ClangParams, RequestedVersion},
rest_api::{RestApiClient, COMMENT_MARKER, USER_OUTREACH},
rest_api::{COMMENT_MARKER, RestApiClient, USER_OUTREACH},
};
pub mod clang_format;
use clang_format::run_clang_format;
pub mod clang_tidy;
use clang_tidy::{run_clang_tidy, CompilationUnit};
use clang_tidy::{CompilationUnit, run_clang_tidy};

#[derive(Debug)]
pub enum ClangTool {
Expand Down Expand Up @@ -229,14 +229,14 @@ pub async fn capture_clang_tools_output(
}

// parse database (if provided) to match filenames when parsing clang-tidy's stdout
if let Some(db_path) = &clang_params.database {
if let Ok(db_str) = fs::read(db_path.join("compile_commands.json")) {
clang_params.database_json = Some(
// A compilation database should be UTF-8 encoded, but file paths are not; use lossy conversion.
serde_json::from_str::<Vec<CompilationUnit>>(&String::from_utf8_lossy(&db_str))
.with_context(|| "Failed to parse compile_commands.json")?,
)
}
if let Some(db_path) = &clang_params.database
&& let Ok(db_str) = fs::read(db_path.join("compile_commands.json"))
{
clang_params.database_json = Some(
// A compilation database should be UTF-8 encoded, but file paths are not; use lossy conversion.
serde_json::from_str::<Vec<CompilationUnit>>(&String::from_utf8_lossy(&db_str))
.with_context(|| "Failed to parse compile_commands.json")?,
)
};

let mut executors = JoinSet::new();
Expand Down Expand Up @@ -503,24 +503,26 @@ mod tests {
let req_version = RequestedVersion::from_str(requirement).unwrap();
let tool_exe = CLANG_FORMAT.get_exe_path(&req_version);
println!("tool_exe: {:?}", tool_exe);
assert!(tool_exe.is_ok_and(|val| val
.file_name()
.unwrap()
.to_string_lossy()
.to_string()
.contains(CLANG_FORMAT.as_str())));
assert!(tool_exe.is_ok_and(|val| {
val.file_name()
.unwrap()
.to_string_lossy()
.to_string()
.contains(CLANG_FORMAT.as_str())
}));
}

#[test]
fn get_exe_by_default() {
let tool_exe = CLANG_FORMAT.get_exe_path(&RequestedVersion::from_str("").unwrap());
println!("tool_exe: {:?}", tool_exe);
assert!(tool_exe.is_ok_and(|val| val
.file_name()
.unwrap()
.to_string_lossy()
.to_string()
.contains(CLANG_FORMAT.as_str())));
assert!(tool_exe.is_ok_and(|val| {
val.file_name()
.unwrap()
.to_string_lossy()
.to_string()
.contains(CLANG_FORMAT.as_str())
}));
}

#[test]
Expand All @@ -531,12 +533,13 @@ mod tests {
println!("binary exe path: {bin_path}");
let tool_exe = CLANG_FORMAT.get_exe_path(&RequestedVersion::from_str(bin_path).unwrap());
println!("tool_exe: {:?}", tool_exe);
assert!(tool_exe.is_ok_and(|val| val
.file_name()
.unwrap()
.to_string_lossy()
.to_string()
.contains(TOOL_NAME)));
assert!(tool_exe.is_ok_and(|val| {
val.file_name()
.unwrap()
.to_string_lossy()
.to_string()
.contains(TOOL_NAME)
}));
}

#[test]
Expand Down
5 changes: 3 additions & 2 deletions cpp-linter/src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ use std::{path::PathBuf, str::FromStr};

// non-std crates
use clap::{
ArgAction, Args, Parser, Subcommand, ValueEnum,
builder::{FalseyValueParser, NonEmptyStringValueParser},
value_parser, ArgAction, Args, Parser, Subcommand, ValueEnum,
value_parser,
};

mod structs;
Expand Down Expand Up @@ -453,7 +454,7 @@ pub fn convert_extra_arg_val(args: &[String]) -> Vec<String> {

#[cfg(test)]
mod test {
use super::{convert_extra_arg_val, Cli};
use super::{Cli, convert_extra_arg_val};
use clap::Parser;

#[test]
Expand Down
6 changes: 3 additions & 3 deletions cpp-linter/src/cli/structs.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use std::{fmt::Display, path::PathBuf, str::FromStr};

use anyhow::{anyhow, Error};
use clap::{builder::PossibleValue, ValueEnum};
use anyhow::{Error, anyhow};
use clap::{ValueEnum, builder::PossibleValue};
use semver::VersionReq;

use super::Cli;
use crate::{
clang_tools::clang_tidy::CompilationUnit,
common_fs::{normalize_path, FileFilter},
common_fs::{FileFilter, normalize_path},
};

#[derive(Debug, Clone, PartialEq, Eq, Default)]
Expand Down
20 changes: 11 additions & 9 deletions cpp-linter/src/common_fs/file_filter.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use anyhow::{anyhow, Context, Result};
use anyhow::{Context, Result, anyhow};
use fast_glob::glob_match;
use std::{
fs,
Expand Down Expand Up @@ -257,14 +257,16 @@ mod tests {
let files = file_filter.list_source_files(".").unwrap();
assert!(!files.is_empty());
for file in files {
assert!(extensions.contains(
&file
.name
.extension()
.unwrap_or_default()
.to_string_lossy()
.to_string()
));
assert!(
extensions.contains(
&file
.name
.extension()
.unwrap_or_default()
.to_string_lossy()
.to_string()
)
);
}
}
}
14 changes: 7 additions & 7 deletions cpp-linter/src/common_fs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use anyhow::{Context, Result};

use crate::clang_tools::clang_format::FormatAdvice;
use crate::clang_tools::clang_tidy::TidyAdvice;
use crate::clang_tools::{make_patch, MakeSuggestions, ReviewComments, Suggestion};
use crate::clang_tools::{MakeSuggestions, ReviewComments, Suggestion, make_patch};
use crate::cli::LinesChangedOnly;
mod file_filter;
pub use file_filter::FileFilter;
Expand Down Expand Up @@ -147,11 +147,11 @@ impl FileObj {
fs::read(&self.name).with_context(|| "Failed to read original contents of file")?;
let file_name = self.name.to_str().unwrap_or_default().replace("\\", "/");
let file_path = Path::new(&file_name);
if let Some(advice) = &self.format_advice {
if let Some(patched) = &advice.patched {
let mut patch = make_patch(file_path, patched, &original_content)?;
advice.get_suggestions(review_comments, self, &mut patch, summary_only)?;
}
if let Some(advice) = &self.format_advice
&& let Some(patched) = &advice.patched
{
let mut patch = make_patch(file_path, patched, &original_content)?;
advice.get_suggestions(review_comments, self, &mut patch, summary_only)?;
}

if let Some(advice) = &self.tidy_advice {
Expand Down Expand Up @@ -266,7 +266,7 @@ mod test {
use std::path::PathBuf;
use std::{env::current_dir, fs};

use super::{get_line_count_from_offset, normalize_path, FileObj};
use super::{FileObj, get_line_count_from_offset, normalize_path};
use crate::cli::LinesChangedOnly;

// *********************** tests for normalized paths
Expand Down
29 changes: 17 additions & 12 deletions cpp-linter/src/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,10 +180,10 @@ mod brute_force_parse_diff {
if let Some(captures) = diff_file_name.captures(front_matter) {
return Some(captures.get(1).unwrap().as_str());
}
if front_matter.trim_start().starts_with("similarity") {
if let Some(captures) = diff_renamed_file.captures(front_matter) {
return Some(captures.get(1).unwrap().as_str());
}
if front_matter.trim_start().starts_with("similarity")
&& let Some(captures) = diff_renamed_file.captures(front_matter)
{
return Some(captures.get(1).unwrap().as_str());
}
if !diff_binary_file.is_match(front_matter) {
log::warn!("Unrecognized diff starting with:\n{}", front_matter);
Expand Down Expand Up @@ -311,11 +311,13 @@ rename to /tests/demo/some source.c
&LinesChangedOnly::Off,
);
assert!(!files.is_empty());
assert!(files
.first()
.unwrap()
.name
.ends_with("tests/demo/some source.c"));
assert!(
files
.first()
.unwrap()
.name
.ends_with("tests/demo/some source.c")
);
}

#[test]
Expand Down Expand Up @@ -415,12 +417,12 @@ mod test {
}
}

use tempfile::{tempdir, TempDir};
use tempfile::{TempDir, tempdir};

use crate::{
cli::LinesChangedOnly,
common_fs::FileFilter,
rest_api::{github::GithubApiClient, RestApiClient},
rest_api::{RestApiClient, github::GithubApiClient},
};

fn get_temp_dir() -> TempDir {
Expand All @@ -445,7 +447,10 @@ mod test {
let rest_api_client = GithubApiClient::new();
let file_filter = FileFilter::new(&["target".to_string()], extensions.to_owned());
set_current_dir(tmp).unwrap();
env::set_var("CI", "false"); // avoid use of REST API when testing in CI
// avoid use of REST API when testing in CI
unsafe {
env::set_var("CI", "false");
}
rest_api_client
.unwrap()
.get_list_of_changed_files(&file_filter, &LinesChangedOnly::Off)
Expand Down
Loading
Loading