Skip to content

Commit 53b1f52

Browse files
committed
WIP: use log crate
1 parent c5b5625 commit 53b1f52

File tree

4 files changed

+52
-82
lines changed

4 files changed

+52
-82
lines changed

.github/actions/clippy-annotation-reporter/src/analyzer.rs

Lines changed: 31 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
//! including getting changed files, comparing branches, and producing analysis results.
88
99
use anyhow::{Context as _, Result};
10+
use log::{debug, error, info};
1011
use octocrab::params::pulls::MediaType::Raw;
1112
use octocrab::Octocrab;
1213
use regex::Regex;
@@ -70,7 +71,7 @@ fn analyze_annotations(
7071
head_branch: &str,
7172
rules: &[String],
7273
) -> Result<AnalysisResult> {
73-
println!("Analyzing clippy annotations in {} files...", files.len());
74+
debug!("Analyzing clippy annotations in {} files...", files.len());
7475

7576
// Create a regex for matching clippy allow annotations
7677
let rule_pattern = rules.join("|");
@@ -80,25 +81,22 @@ fn analyze_annotations(
8081
))
8182
.context("Failed to compile annotation regex")?;
8283

83-
let mut base_annotations = Vec::with_capacity(files.len() * 3);
84-
let mut head_annotations = Vec::with_capacity(files.len() * 3);
85-
let mut changed_files = HashSet::with_capacity(files.len());
84+
let mut base_annotations = Vec::new();
85+
let mut head_annotations = Vec::new();
86+
let mut changed_files = HashSet::new();
8687

8788
// Cache for rule Rc instances to avoid duplicates
89+
// TODO: EK - why?
8890
let mut rule_cache = HashMap::new();
8991

90-
// Process each file
9192
for file in files {
9293
changed_files.insert(file.clone());
9394

9495
// Get file content from base branch
9596
let base_content = match get_file_content(file, base_branch) {
9697
Ok(content) => content,
9798
Err(e) => {
98-
println!(
99-
"Warning: Failed to get {} content from {}: {}",
100-
file, base_branch, e
101-
);
99+
error!("Failed to get {} content from {}: {}", file, base_branch, e);
102100
String::new()
103101
}
104102
};
@@ -107,10 +105,7 @@ fn analyze_annotations(
107105
let head_content = match get_file_content(file, head_branch) {
108106
Ok(content) => content,
109107
Err(e) => {
110-
println!(
111-
"Warning: Failed to get {} content from {}: {}",
112-
file, head_branch, e
113-
);
108+
error!("Failed to get {} content from {}: {}", file, head_branch, e);
114109
String::new()
115110
}
116111
};
@@ -142,7 +137,7 @@ fn analyze_annotations(
142137
let base_crate_counts = count_annotations_by_crate(&base_annotations);
143138
let head_crate_counts = count_annotations_by_crate(&head_annotations);
144139

145-
println!(
140+
info!(
146141
"Analysis complete. Found {} annotations in base branch and {} in head branch",
147142
base_annotations.len(),
148143
head_annotations.len()
@@ -166,7 +161,7 @@ async fn get_changed_files(
166161
repo: &str,
167162
pr_number: u64,
168163
) -> Result<Vec<String>> {
169-
println!("Getting changed files from PR #{}...", pr_number);
164+
info!("Getting changed files from PR #{}...", pr_number);
170165

171166
let files = octocrab
172167
.pulls(owner, repo)
@@ -182,14 +177,14 @@ async fn get_changed_files(
182177
.map(|file| file.filename)
183178
.collect();
184179

185-
println!("Found {} changed Rust files", rust_files.len());
180+
info!("Found {} changed Rust files", rust_files.len());
186181

187182
Ok(rust_files)
188183
}
189184

190185
/// Get file content from a specific branch
191186
fn get_file_content(file: &str, branch: &str) -> Result<String> {
192-
println!("Getting content for {} from {}", file, branch);
187+
debug!("Getting content for {} from {}", file, branch);
193188

194189
let output = Command::new("git")
195190
.args(["show", &format!("{}:{}", branch, file)])
@@ -316,7 +311,7 @@ fn count_annotations_by_crate(annotations: &[ClippyAnnotation]) -> HashMap<Rc<St
316311

317312
/// Get all Rust files in the repository
318313
fn get_all_rust_files() -> Result<Vec<String>> {
319-
println!("Getting all Rust files in the repository...");
314+
info!("Getting all Rust files in the repository...");
320315

321316
// Use git ls-files to get all tracked Rust files
322317
let output = Command::new("git")
@@ -333,7 +328,7 @@ fn get_all_rust_files() -> Result<Vec<String>> {
333328

334329
let rust_files: Vec<String> = files.lines().map(|line| line.to_owned()).collect();
335330

336-
println!("Found {} Rust files in total", rust_files.len());
331+
info!("Found {} Rust files in total", rust_files.len());
337332

338333
Ok(rust_files)
339334
}
@@ -345,7 +340,7 @@ fn analyze_all_files_for_crates(
345340
head_branch: &str,
346341
rules: &[String],
347342
) -> Result<(HashMap<Rc<String>, usize>, HashMap<Rc<String>, usize>)> {
348-
println!(
343+
info!(
349344
"Analyzing all {} Rust files for crate-level statistics...",
350345
files.len()
351346
);
@@ -364,35 +359,8 @@ fn analyze_all_files_for_crates(
364359
let mut rule_cache = HashMap::new();
365360
// Process each file
366361
for file in files {
367-
// Get file content from base branch
368-
let base_content = match get_file_content(file, base_branch) {
369-
Ok(content) => content,
370-
Err(e) => {
371-
// Skip errors for files that might not exist in one branch
372-
if !e.to_string().contains("did not match any file") {
373-
println!(
374-
"Warning: Failed to get {} content from {}: {}",
375-
file, base_branch, e
376-
);
377-
}
378-
String::new()
379-
}
380-
};
381-
382-
// Get file content from head branch
383-
let head_content = match get_file_content(file, head_branch) {
384-
Ok(content) => content,
385-
Err(e) => {
386-
// Skip errors for files that might not exist in one branch
387-
if !e.to_string().contains("did not match any file") {
388-
println!(
389-
"Warning: Failed to get {} content from {}: {}",
390-
file, head_branch, e
391-
);
392-
}
393-
String::new()
394-
}
395-
};
362+
let base_content = get_branch_content(file, base_branch);
363+
let head_content = get_branch_content(file, head_branch);
396364

397365
// Find annotations in base branch
398366
find_annotations(
@@ -419,6 +387,20 @@ fn analyze_all_files_for_crates(
419387
Ok((base_crate_counts, head_crate_counts))
420388
}
421389

390+
/// Get file content from a branch, handling common errors
391+
fn get_branch_content(file: &str, branch: &str) -> String {
392+
match get_file_content(file, branch) {
393+
Ok(content) => content,
394+
Err(e) => {
395+
// Skip errors for files that might not exist in one branch
396+
if !e.to_string().contains("did not match any file") {
397+
log::warn!("Failed to get {} content from {}: {}", file, branch, e);
398+
}
399+
String::new()
400+
}
401+
}
402+
}
403+
422404
#[cfg(test)]
423405
mod tests {
424406
use super::*;

.github/actions/clippy-annotation-reporter/src/commenter.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
//! including finding existing comments and updating or creating comments.
88
99
use anyhow::{Context as _, Result};
10+
use log::{debug, error, info};
1011
use octocrab::Octocrab;
1112

1213
/// Post or update a comment on a PR with the given report
@@ -25,27 +26,25 @@ pub async fn post_comment(
2526
let report_with_signature = format!("{}\n\n{}", report, signature);
2627

2728
// Search for existing comment by the bot
28-
println!("Checking for existing comment on PR #{}", pr_number);
29+
info!("Checking for existing comment on PR #{}", pr_number);
2930
let existing_comment =
3031
find_existing_comment(octocrab, owner, repo, pr_number, signature).await?;
3132

3233
// Update existing comment or create a new one
3334
if let Some(comment_id) = existing_comment {
34-
println!("Updating existing comment #{}", comment_id);
35+
info!("Updating existing comment #{}", comment_id);
3536
octocrab
3637
.issues(owner, repo)
3738
.update_comment(comment_id.into(), report_with_signature)
3839
.await
3940
.context("Failed to update existing comment")?;
40-
println!("Comment updated successfully!");
4141
} else {
42-
println!("Creating new comment on PR #{}", pr_number);
42+
info!("Creating new comment on PR #{}", pr_number);
4343
octocrab
4444
.issues(owner, repo)
4545
.create_comment(pr_number, report_with_signature)
4646
.await
4747
.context("Failed to post comment to PR")?;
48-
println!("Comment created successfully!");
4948
}
5049

5150
Ok(())
@@ -91,7 +90,7 @@ async fn find_existing_comment(
9190
}
9291
Err(e) => {
9392
// TODO: EK - Handle error more gracefully
94-
println!("Warning: Failed to fetch next page of comments: {}", e);
93+
error!("Warning: Failed to fetch next page of comments: {}", e);
9594
break;
9695
}
9796
}

.github/actions/clippy-annotation-reporter/src/config.rs

Lines changed: 11 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
99
use anyhow::{Context as _, Result};
1010
use clap::Parser;
11+
use log::{debug, warn};
1112
use serde_json::Value;
1213
use std::env;
1314
use std::fs;
@@ -81,9 +82,6 @@ impl GitHubContext {
8182
let event_path = env::var("GITHUB_EVENT_PATH")
8283
.context("GITHUB_EVENT_PATH environment variable not set")?;
8384

84-
println!("Event name: {}", event_name);
85-
println!("Event path: {}", event_path);
86-
8785
let event_data =
8886
fs::read_to_string(event_path).context("Failed to read GitHub event file")?;
8987

@@ -99,31 +97,22 @@ impl GitHubContext {
9997

10098
// Direct access to base.ref
10199
let base_ref = match event_json["pull_request"]["base"]["ref"].as_str() {
102-
Some(val) => {
103-
println!("Successfully found base.ref in event data: {}", val);
104-
val.to_owned()
105-
}
100+
Some(val) => val.to_owned(),
106101
None => {
107-
println!(
108-
"Warning: Could not extract base.ref as string, raw value: {:?}",
109-
event_json["pull_request"]["base"]["ref"]
102+
warn!(
103+
"Could not extract base.ref as string, Falling back to main as base branch",
110104
);
111105

112-
// Fallback to main if we can't extract the value
113-
println!("Falling back to 'main' as base branch");
114106
"main".to_owned()
115107
}
116108
};
117109

118110
// Direct access to head.ref
119111
let head_ref = match event_json["pull_request"]["head"]["ref"].as_str() {
120-
Some(val) => {
121-
println!("Successfully found head.ref in event data: {}", val);
122-
val.to_owned()
123-
}
112+
Some(val) => val.to_owned(),
124113
None => {
125-
println!("Warning: Could not extract head.ref as string");
126-
// We'll use the current branch as fallback
114+
warn!("Warning: Could not extract head.ref as string");
115+
127116
String::new()
128117
}
129118
};
@@ -136,9 +125,10 @@ impl GitHubContext {
136125
}
137126
};
138127

139-
println!("Extracted PR number: {}", pr_number);
140-
println!("Extracted base branch: {}", base_ref);
141-
println!("Extracted head branch: {}", head_ref);
128+
debug!(
129+
"Extracted PR: {}, base: {}, head: {}",
130+
pr_number, base_ref, head_ref
131+
);
142132

143133
Ok(GitHubContext {
144134
repository,
@@ -214,7 +204,6 @@ impl Config {
214204
let owner = parts[0].to_owned();
215205
let repo = parts[1].to_owned();
216206

217-
// Parse rules list
218207
let rules = args.parse_rules();
219208

220209
Ok(Config {

.github/actions/clippy-annotation-reporter/src/main.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// SPDX-License-Identifier: Apache-2.0
33

44
use anyhow::{Context as _, Result};
5+
use log::info;
56
use octocrab::Octocrab;
67

78
mod analyzer;
@@ -14,14 +15,13 @@ use crate::report_generator::generate_report;
1415

1516
#[tokio::main]
1617
async fn main() -> Result<()> {
17-
// Initialize logger
18-
// TODO: EK - Do we even want to use env_logger here?
1918
env_logger::init();
2019

21-
println!("Clippy Annotation Reporter starting...");
20+
info!("Clippy Annotation Reporter starting...");
2221

2322
let config = ConfigBuilder::new().build()?;
2423

24+
// TODO: EK - Should we use context here?
2525
let octocrab = Octocrab::builder()
2626
.personal_token(config.token.clone())
2727
.build()
@@ -41,7 +41,7 @@ async fn main() -> Result<()> {
4141
Ok(result) => result,
4242
Err(e) => {
4343
if e.to_string().contains("No Rust files changed") {
44-
println!("No Rust files changed in this PR, nothing to analyze.");
44+
info!("No Rust files changed in this PR, nothing to analyze.");
4545
return Ok(());
4646
}
4747
return Err(e);
@@ -66,7 +66,7 @@ async fn main() -> Result<()> {
6666
)
6767
.await?;
6868

69-
println!("Process completed successfully!");
69+
info!("Process completed successfully!");
7070

7171
Ok(())
7272
}

0 commit comments

Comments
 (0)