Skip to content

refactor: use Client instance by reference #141

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 21, 2025
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
5 changes: 3 additions & 2 deletions cpp-linter/src/common_fs/file_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ impl FileFilter {
for line in read_buf.split('\n') {
if line.trim_start().starts_with("path") {
assert!(line.find('=').unwrap() > 0);
let submodule = String::from("./") + line.split('=').last().unwrap().trim();
let submodule =
String::from("./") + line.split('=').next_back().unwrap().trim();
log::debug!("Found submodule: {submodule}");
let mut is_ignored = true;
for pat in &self.not_ignored {
Expand Down Expand Up @@ -159,7 +160,7 @@ impl FileFilter {
let mut is_hidden = false;
let parent = path
.components()
.last()
.next_back()
.ok_or(anyhow!("parent directory not known for {path:?}"))?;
if parent.as_os_str().to_str().unwrap().starts_with('.') {
is_hidden = true;
Expand Down
43 changes: 34 additions & 9 deletions cpp-linter/src/logger.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
//! A module to initialize and customize the logger object used in (most) stdout.

use std::env;
use std::{
env,
io::{stdout, Write},
};

use colored::{control::set_override, Colorize};
use log::{Level, LevelFilter, Metadata, Record};
use log::{Level, LevelFilter, Log, Metadata, Record};

#[derive(Default)]
struct SimpleLogger;
Expand All @@ -21,21 +24,43 @@ impl SimpleLogger {
}
}

impl log::Log for SimpleLogger {
impl Log for SimpleLogger {
fn enabled(&self, metadata: &Metadata) -> bool {
metadata.level() <= log::max_level()
}

fn log(&self, record: &Record) {
let mut stdout = stdout().lock();
if record.target() == "CI_LOG_GROUPING" {
// this log is meant to manipulate a CI workflow's log grouping
println!("{}", record.args());
writeln!(stdout, "{}", record.args()).expect("Failed to write log command to stdout");
stdout
.flush()
.expect("Failed to flush log command to stdout");
} else if self.enabled(record.metadata()) {
println!(
"[{}]: {}",
Self::level_color(&record.level()),
record.args()
);
let module = record.module_path();
if module.is_none_or(|v| v.starts_with("cpp_linter")) {
writeln!(
stdout,
"[{}]: {}",
Self::level_color(&record.level()),
record.args()
)
.expect("Failed to write log message to stdout");
} else {
writeln!(
stdout,
"[{}]{{{}:{}}}: {}",
Self::level_color(&record.level()),
module.unwrap(), // safe to unwrap here because the None case is caught above
record.line().unwrap_or_default(),
record.args()
)
.expect("Failed to write detailed log message to stdout");
}
stdout
.flush()
.expect("Failed to flush log message to stdout");
}
}

Expand Down
13 changes: 4 additions & 9 deletions cpp-linter/src/rest_api/github/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use reqwest::{
};

// project specific modules/crates
use super::{RestApiClient, RestApiRateLimitHeaders};
use super::{send_api_request, RestApiClient, RestApiRateLimitHeaders};
use crate::clang_tools::clang_format::tally_format_advice;
use crate::clang_tools::clang_tidy::tally_tidy_advice;
use crate::clang_tools::ClangVersions;
Expand Down Expand Up @@ -148,14 +148,9 @@ impl RestApiClient for GithubApiClient {
None,
Some(diff_header),
)?;
let response = Self::send_api_request(
self.client.clone(),
request,
self.rate_limit_headers.to_owned(),
0,
)
.await
.with_context(|| "Failed to get list of changed files.")?;
let response = send_api_request(&self.client, request, &self.rate_limit_headers)
.await
.with_context(|| "Failed to get list of changed files.")?;
if response.status().is_success() {
Ok(parse_diff_from_buf(
&response.bytes().await?,
Expand Down
70 changes: 16 additions & 54 deletions cpp-linter/src/rest_api/github/specific_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use crate::{
cli::{FeedbackInput, LinesChangedOnly},
common_fs::{FileFilter, FileObj},
git::parse_diff_from_buf,
rest_api::{RestApiRateLimitHeaders, COMMENT_MARKER, USER_AGENT},
rest_api::{send_api_request, RestApiRateLimitHeaders, COMMENT_MARKER, USER_AGENT},
};

use super::{
Expand Down Expand Up @@ -94,14 +94,9 @@ impl GithubApiClient {
while let Some(ref endpoint) = url {
let request =
Self::make_api_request(&self.client, endpoint.as_str(), Method::GET, None, None)?;
let response = Self::send_api_request(
self.client.clone(),
request,
self.rate_limit_headers.clone(),
0,
)
.await
.with_context(|| "Failed to get paginated list of changed files")?;
let response = send_api_request(&self.client, request, &self.rate_limit_headers)
.await
.with_context(|| "Failed to get paginated list of changed files")?;
url = Self::try_next_page(response.headers());
let files_list = if self.event_name != "pull_request" {
let json_value: PushEventFiles = serde_json::from_str(&response.text().await?)
Expand Down Expand Up @@ -233,14 +228,7 @@ impl GithubApiClient {
Some(serde_json::json!(&payload).to_string()),
None,
)?;
match Self::send_api_request(
self.client.clone(),
request,
self.rate_limit_headers.to_owned(),
0,
)
.await
{
match send_api_request(&self.client, request, &self.rate_limit_headers).await {
Ok(response) => {
Self::log_response(response, "Failed to post thread comment").await;
}
Expand Down Expand Up @@ -270,13 +258,7 @@ impl GithubApiClient {
while let Some(ref endpoint) = comments_url {
let request =
Self::make_api_request(&self.client, endpoint.as_str(), Method::GET, None, None)?;
let result = Self::send_api_request(
self.client.clone(),
request,
self.rate_limit_headers.to_owned(),
0,
)
.await;
let result = send_api_request(&self.client, request, &self.rate_limit_headers).await;
match result {
Err(e) => {
log::error!("Failed to get list of existing thread comments: {e:?}");
Expand Down Expand Up @@ -330,11 +312,10 @@ impl GithubApiClient {
None,
None,
)?;
match Self::send_api_request(
self.client.clone(),
match send_api_request(
&self.client,
req,
self.rate_limit_headers.to_owned(),
0,
&self.rate_limit_headers,
)
.await
{
Expand Down Expand Up @@ -391,12 +372,7 @@ impl GithubApiClient {
// if we got here, then we know that it is a self.pull_request is a valid value
.join(self.pull_request.to_string().as_str())?;
let request = Self::make_api_request(&self.client, url.as_str(), Method::GET, None, None)?;
let response = Self::send_api_request(
self.client.clone(),
request,
self.rate_limit_headers.clone(),
0,
);
let response = send_api_request(&self.client, request, &self.rate_limit_headers);

let url = Url::parse(format!("{}/", url).as_str())?.join("reviews")?;
let dismissal = self.dismiss_outdated_reviews(&url);
Expand Down Expand Up @@ -462,22 +438,15 @@ impl GithubApiClient {
dismissal.await?; // free up the `url` variable
let request = Self::make_api_request(
&self.client,
url.clone(),
url,
Method::POST,
Some(
serde_json::to_string(&payload)
.with_context(|| "Failed to serialize PR review to json string")?,
),
None,
)?;
match Self::send_api_request(
self.client.clone(),
request,
self.rate_limit_headers.clone(),
0,
)
.await
{
match send_api_request(&self.client, request, &self.rate_limit_headers).await {
Ok(response) => {
if !response.status().is_success() {
Self::log_response(response, "Failed to post a new PR review").await;
Expand All @@ -496,13 +465,7 @@ impl GithubApiClient {
while let Some(ref endpoint) = url_ {
let request =
Self::make_api_request(&self.client, endpoint.as_str(), Method::GET, None, None)?;
let result = Self::send_api_request(
self.client.clone(),
request,
self.rate_limit_headers.clone(),
0,
)
.await;
let result = send_api_request(&self.client, request, &self.rate_limit_headers).await;
match result {
Err(e) => {
log::error!("Failed to get a list of existing PR reviews: {e:?}");
Expand Down Expand Up @@ -538,11 +501,10 @@ impl GithubApiClient {
Some(REVIEW_DISMISSAL.to_string()),
None,
) {
match Self::send_api_request(
self.client.clone(),
match send_api_request(
&self.client,
req,
self.rate_limit_headers.clone(),
0,
&self.rate_limit_headers,
)
.await
{
Expand Down
Loading