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
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "codeowners"
version = "0.2.16"
version = "0.2.17"
edition = "2024"

[profile.release]
Expand Down
4 changes: 2 additions & 2 deletions src/cache/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub struct GlobalCache {
file_owner_cache: Option<Box<Mutex<HashMap<PathBuf, FileOwnerCacheEntry>>>>,
}

const DEFAULT_CACHE_CAPACITY: usize = 10000;
const DEFAULT_CACHE_CAPACITY: usize = 50000;

impl Caching for GlobalCache {
fn get_file_owner(&self, path: &Path) -> Result<Option<FileOwnerCacheEntry>, Error> {
Expand Down Expand Up @@ -62,7 +62,7 @@ impl Caching for GlobalCache {

fn delete_cache(&self) -> Result<(), Error> {
let cache_path = self.get_cache_path();
dbg!("deleting", &cache_path);
tracing::debug!("Deleting cache file: {}", cache_path.display());
fs::remove_file(cache_path).change_context(Error::Io)
}
}
Expand Down
10 changes: 8 additions & 2 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@ enum Command {
help = "Find the owner from the CODEOWNERS file and just return the team name and yml path"
)]
from_codeowners: bool,
#[arg(short, long, default_value = "false", help = "Output the result in JSON format")]
json: bool,
name: String,
},

#[clap(about = "Finds code ownership information for a given team ", visible_alias = "t")]
#[clap(about = "Finds code ownership information for a given team", visible_alias = "t")]
ForTeam { name: String },

#[clap(
Expand Down Expand Up @@ -113,7 +115,11 @@ pub fn cli() -> Result<RunResult, RunnerError> {
Command::Validate => runner::validate(&run_config, vec![]),
Command::Generate { skip_stage } => runner::generate(&run_config, !skip_stage),
Command::GenerateAndValidate { skip_stage } => runner::generate_and_validate(&run_config, vec![], !skip_stage),
Command::ForFile { name, from_codeowners } => runner::for_file(&run_config, &name, from_codeowners),
Command::ForFile {
name,
from_codeowners,
json,
} => runner::for_file(&run_config, &name, from_codeowners, json),
Command::ForTeam { name } => runner::for_team(&run_config, &name),
Command::DeleteCache => runner::delete_cache(&run_config),
Command::CrosscheckOwners => runner::crosscheck_owners(&run_config),
Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ fn maybe_print_errors(result: RunResult) -> Result<(), RunnerError> {
for msg in result.validation_errors {
println!("{}", msg);
}
process::exit(-1);
process::exit(1);
}

Ok(())
Expand Down
10 changes: 6 additions & 4 deletions src/ownership.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,19 +59,21 @@ impl TeamOwnership {
impl Display for FileOwner {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let sources = if self.sources.is_empty() {
"Unowned".to_string()
"".to_string()
} else {
self.sources
let sources_str = self
.sources
.iter()
.sorted_by_key(|source| source.to_string())
.map(|source| source.to_string())
.collect::<Vec<_>>()
.join("\n- ")
.join("\n- ");
format!("\n- {}", sources_str)
};

write!(
f,
"Team: {}\nGithub Team: {}\nTeam YML: {}\nDescription:\n- {}",
"Team: {}\nGithub Team: {}\nTeam YML: {}\nDescription:{}",
self.team.name, self.team.github_team, self.team_config_file_path, sources
)
}
Expand Down
35 changes: 12 additions & 23 deletions src/ownership/codeowners_file_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,7 @@ use fast_glob::glob_match;
use memoize::memoize;
use rayon::prelude::*;
use regex::Regex;
use std::{
collections::HashMap,
error::Error,
fs,
io::Error as IoError,
path::{Path, PathBuf},
};
use std::{collections::HashMap, error::Error, fs, io::Error as IoError, path::PathBuf};

use super::file_generator::compare_lines;

Expand Down Expand Up @@ -44,16 +38,7 @@ impl Parser {
return Ok(HashMap::new());
}

let codeowners_entries: Vec<(String, String)> =
build_codeowners_lines_in_priority(self.codeowners_file_path.to_string_lossy().into_owned())
.iter()
.map(|line| {
line.split_once(' ')
.map(|(glob, team_name)| (glob.to_string(), team_name.to_string()))
.ok_or_else(|| IoError::new(std::io::ErrorKind::InvalidInput, "Invalid line"))
})
.collect::<Result<_, IoError>>()
.map_err(|e| Box::new(e) as Box<dyn Error>)?;
let codeowners_entries = parse_codeowners_entries(self.codeowners_file_path.to_string_lossy().into_owned());
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A little refactoring for clarity


let teams_by_name = teams_by_github_team_name(self.absolute_team_files_globs());

Expand All @@ -71,11 +56,6 @@ impl Parser {
Ok(result)
}

pub fn team_from_file_path(&self, file_path: &Path) -> Result<Option<Team>, Box<dyn Error>> {
let teams = self.teams_from_files_paths(&[file_path.to_path_buf()])?;
Ok(teams.get(file_path.to_string_lossy().into_owned().as_str()).cloned().flatten())
}

fn absolute_team_files_globs(&self) -> Vec<String> {
self.team_file_globs
.iter()
Expand Down Expand Up @@ -111,7 +91,6 @@ fn teams_by_github_team_name(team_file_glob: Vec<String>) -> HashMap<String, Tea
teams
}

#[memoize]
fn build_codeowners_lines_in_priority(codeowners_file_path: String) -> Vec<String> {
let codeowners_file = match fs::read_to_string(codeowners_file_path) {
Ok(codeowners_file) => codeowners_file,
Expand All @@ -124,6 +103,16 @@ fn build_codeowners_lines_in_priority(codeowners_file_path: String) -> Vec<Strin
stripped_lines_by_priority(&codeowners_file)
}

fn parse_codeowners_entries(codeowners_file_path: String) -> Vec<(String, String)> {
build_codeowners_lines_in_priority(codeowners_file_path)
.iter()
.filter_map(|line| {
line.split_once(' ')
.map(|(glob, team_name)| (glob.to_string(), team_name.to_string()))
})
.collect()
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct Section {
heading: String,
Expand Down
21 changes: 0 additions & 21 deletions src/ownership/codeowners_query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,6 @@ use std::path::{Path, PathBuf};
use crate::ownership::codeowners_file_parser::Parser;
use crate::project::Team;

pub(crate) fn team_for_file_from_codeowners(
project_root: &Path,
codeowners_file_path: &Path,
team_file_globs: &[String],
file_path: &Path,
) -> Result<Option<Team>, String> {
let relative_file_path = if file_path.is_absolute() {
crate::path_utils::relative_to_buf(project_root, file_path)
} else {
PathBuf::from(file_path)
};

let parser = Parser {
codeowners_file_path: codeowners_file_path.to_path_buf(),
project_root: project_root.to_path_buf(),
team_file_globs: team_file_globs.to_vec(),
};

parser.team_from_file_path(&relative_file_path).map_err(|e| e.to_string())
}

pub(crate) fn teams_for_files_from_codeowners(
project_root: &Path,
codeowners_file_path: &Path,
Expand Down
6 changes: 3 additions & 3 deletions src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,9 +158,9 @@ pub enum Error {
impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Io => fmt.write_str("Error::Io"),
Error::SerdeYaml => fmt.write_str("Error::SerdeYaml"),
Error::SerdeJson => fmt.write_str("Error::SerdeJson"),
Error::Io => fmt.write_str("IO operation failed"),
Error::SerdeYaml => fmt.write_str("YAML serialization/deserialization failed"),
Error::SerdeJson => fmt.write_str("JSON serialization/deserialization failed"),
}
}
}
Expand Down
10 changes: 9 additions & 1 deletion src/project_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,9 @@ impl<'a> ProjectBuilder<'a> {
}
}

#[instrument(level = "debug", skip_all)]
#[instrument(level = "debug", skip_all, fields(base_path = %self.base_path.display()))]
pub fn build(&mut self) -> Result<Project, Error> {
tracing::info!("Starting project build");
let mut builder = WalkBuilder::new(&self.base_path);
builder.hidden(false);
builder.follow_links(false);
Expand Down Expand Up @@ -277,6 +278,13 @@ impl<'a> ProjectBuilder<'a> {
.flat_map(|team| vec![(team.name.clone(), team.clone()), (team.github_team.clone(), team.clone())])
.collect();

tracing::info!(
files_count = %project_files.len(),
teams_count = %teams.len(),
packages_count = %packages.len(),
"Project build completed successfully"
);

Ok(Project {
base_path: self.base_path.to_owned(),
files: project_files,
Expand Down
Loading