chore: clippy fix

Signed-off-by: kjuulh <contact@kjuulh.io>
This commit is contained in:
Kasper Juul Hermansen 2023-07-31 13:34:23 +02:00
parent df96de1cd0
commit bc3e091f45
Signed by: kjuulh
GPG Key ID: 9AA7BC13CE474394
11 changed files with 49 additions and 75 deletions

View File

@ -139,7 +139,7 @@ impl ChangeLog<'_> {
let config = Config { let config = Config {
changelog: default_changelog_config( changelog: default_changelog_config(
None, None,
self.release_link.as_ref().map(|rl| rl.as_str()), self.release_link.as_deref(),
), ),
git: default_git_config(), git: default_git_config(),
}; };
@ -151,7 +151,7 @@ impl ChangeLog<'_> {
let config = Config { let config = Config {
changelog: default_changelog_config( changelog: default_changelog_config(
header, header,
self.release_link.as_ref().map(|rl| rl.as_str()), self.release_link.as_deref(),
), ),
git: default_git_config(), git: default_git_config(),
}; };
@ -200,7 +200,7 @@ fn default_commit_parsers() -> Vec<CommitParser> {
] ]
} }
const CHANGELOG_HEADER: &'static str = r#"# Changelog const CHANGELOG_HEADER: &str = r#"# Changelog
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
@ -219,9 +219,9 @@ fn default_changelog_config(header: Option<String>, release_link: Option<&str>)
} }
fn default_changelog_body_config(release_link: Option<&str>) -> String { fn default_changelog_body_config(release_link: Option<&str>) -> String {
const pre: &'static str = r#" const pre: &str = r#"
## [{{ version | trim_start_matches(pat="v") }}]"#; ## [{{ version | trim_start_matches(pat="v") }}]"#;
const post: &'static str = r#" - {{ timestamp | date(format="%Y-%m-%d") }} const post: &str = r#" - {{ timestamp | date(format="%Y-%m-%d") }}
{% for group, commits in commits | group_by(attribute="group") %} {% for group, commits in commits | group_by(attribute="group") %}
### {{ group | upper_first }} ### {{ group | upper_first }}
{% for commit in commits %} {% for commit in commits %}
@ -240,7 +240,6 @@ fn default_changelog_body_config(release_link: Option<&str>) -> String {
} }
pub mod changelog_parser { pub mod changelog_parser {
use std::{fs::read_to_string, path::Path};
use anyhow::Context; use anyhow::Context;
use regex::Regex; use regex::Regex;
@ -252,9 +251,9 @@ pub mod changelog_parser {
/// (in the ..anything.. case, `## ..anything..` is not included in the header) /// (in the ..anything.. case, `## ..anything..` is not included in the header)
pub fn parse_header(changelog: &str) -> Option<String> { pub fn parse_header(changelog: &str) -> Option<String> {
lazy_static::lazy_static! { lazy_static::lazy_static! {
static ref FIRST_RE: Regex = Regex::new(r#"(?s)^(# Changelog|# CHANGELOG|# changelog)(.*)(## Unreleased|## \[Unreleased\])"#).unwrap(); static ref FIRST_RE: Regex = Regex::new(r"(?s)^(# Changelog|# CHANGELOG|# changelog)(.*)(## Unreleased|## \[Unreleased\])").unwrap();
static ref SECOND_RE: Regex = Regex::new(r#"(?s)^(# Changelog|# CHANGELOG|# changelog)(.*)(\n## )"#).unwrap(); static ref SECOND_RE: Regex = Regex::new(r"(?s)^(# Changelog|# CHANGELOG|# changelog)(.*)(\n## )").unwrap();
} }
if let Some(captures) = FIRST_RE.captures(changelog) { if let Some(captures) = FIRST_RE.captures(changelog) {
return Some(format!("{}\n", &captures[0])); return Some(format!("{}\n", &captures[0]));

View File

@ -14,13 +14,9 @@ use crate::{
cliff::{self, changelog_parser}, cliff::{self, changelog_parser},
environment::get_from_environment, environment::get_from_environment,
git_client::VcsClient, git_client::VcsClient,
gitea_client::{GiteaClient, Tag}, gitea_client::GiteaClient,
ui::{ConsoleUi, DynUi}, ui::{ConsoleUi, DynUi},
versioning::{ versioning::{next_version::NextVersion, semver::get_most_significant_version},
conventional_parse::VersionIncrement,
next_version::NextVersion,
semver::{self, get_most_significant_version},
},
}; };
#[derive(Parser)] #[derive(Parser)]
@ -175,7 +171,7 @@ impl Command {
tracing::debug!("running command: config list"); tracing::debug!("running command: config list");
let _config = self.get_config(current_dir.as_path(), stdin)?; let _config = self.get_config(current_dir.as_path(), stdin)?;
self.ui.write_str_ln(&format!("cuddle-config")); self.ui.write_str_ln("cuddle-config");
} }
}, },
Some(Commands::Gitea { command }) => { Some(Commands::Gitea { command }) => {
@ -256,13 +252,13 @@ impl Command {
Some(Commands::Doctor {}) => { Some(Commands::Doctor {}) => {
match std::process::Command::new("git").arg("-v").output() { match std::process::Command::new("git").arg("-v").output() {
Ok(o) => { Ok(o) => {
let stdout = std::str::from_utf8(&o.stdout).unwrap_or("".into()); let stdout = std::str::from_utf8(&o.stdout).unwrap_or("");
self.ui.write_str_ln(&format!("OK: {}", stdout)); self.ui.write_str_ln(&format!("OK: {}", stdout));
} }
Err(e) => { Err(e) => {
self.ui.write_str_ln(&format!( self.ui.write_str_ln(&format!(
"WARNING: git is not installed: {}", "WARNING: git is not installed: {}",
e.to_string() e
)); ));
} }
} }
@ -272,7 +268,7 @@ impl Command {
// 2. Parse the cuddle.please.yaml let cuddle.please.yaml take precedence // 2. Parse the cuddle.please.yaml let cuddle.please.yaml take precedence
// 2a. if not existing use default. // 2a. if not existing use default.
// 2b. if not in a git repo abort. (unless --no-vcs is turned added) // 2b. if not in a git repo abort. (unless --no-vcs is turned added)
let config = self.get_config(&current_dir, stdin)?; let _config = self.get_config(&current_dir, stdin)?;
let owner = self.global.owner.as_ref().expect("owner to be set"); let owner = self.global.owner.as_ref().expect("owner to be set");
let repo = self.global.repo.as_ref().expect("repo to be set"); let repo = self.global.repo.as_ref().expect("repo to be set");
@ -363,7 +359,7 @@ impl Command {
git_client.commit_and_push(next_version.to_string(), self.global.dry_run)?; git_client.commit_and_push(next_version.to_string(), self.global.dry_run)?;
let pr_number = match gitea_client.get_pull_request(owner, repo)? { let _pr_number = match gitea_client.get_pull_request(owner, repo)? {
Some(existing_pr) => { Some(existing_pr) => {
if !self.global.dry_run { if !self.global.dry_run {
gitea_client.update_pull_request( gitea_client.update_pull_request(
@ -495,6 +491,7 @@ pub struct PleaseSettingsConfig {
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Default)]
pub struct PleaseConfig { pub struct PleaseConfig {
pub project: Option<PleaseProjectConfig>, pub project: Option<PleaseProjectConfig>,
pub settings: Option<PleaseSettingsConfig>, pub settings: Option<PleaseSettingsConfig>,
@ -510,14 +507,7 @@ impl PleaseConfig {
} }
} }
impl Default for PleaseConfig {
fn default() -> Self {
Self {
project: None,
settings: None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
struct CuddleEmbeddedPleaseConfig { struct CuddleEmbeddedPleaseConfig {
@ -540,9 +530,9 @@ impl From<CuddlePleaseConfig> for PleaseConfig {
} }
} }
const CUDDLE_FILE_NAME: &'static str = "cuddle"; const CUDDLE_FILE_NAME: &str = "cuddle";
const CUDDLE_CONFIG_FILE_NAME: &'static str = "cuddle.please"; const CUDDLE_CONFIG_FILE_NAME: &str = "cuddle.please";
const YAML_EXTENSION: &'static str = "yaml"; const YAML_EXTENSION: &str = "yaml";
fn get_config(current_dir: &Path, stdin: Option<String>) -> anyhow::Result<PleaseConfig> { fn get_config(current_dir: &Path, stdin: Option<String>) -> anyhow::Result<PleaseConfig> {
let current_cuddle_path = current_dir let current_cuddle_path = current_dir
@ -604,7 +594,7 @@ where
T: Into<PleaseConfig>, T: Into<PleaseConfig>,
{ {
match stdin { match stdin {
Some(content) => match serde_yaml::from_str::<'d, T>(&content) { Some(content) => match serde_yaml::from_str::<'d, T>(content) {
Ok(config) => { Ok(config) => {
return Some(config.into()); return Some(config.into());
} }

View File

@ -25,11 +25,11 @@ pub fn get_from_environment() -> PleaseConfig {
} }
pub fn detect_environment() -> ExecutionEnvironment { pub fn detect_environment() -> ExecutionEnvironment {
if let Some(_) = std::env::var("DRONE").ok() { if std::env::var("DRONE").is_ok() {
return ExecutionEnvironment::Drone; return ExecutionEnvironment::Drone;
} }
return ExecutionEnvironment::Local; ExecutionEnvironment::Local
} }
pub enum ExecutionEnvironment { pub enum ExecutionEnvironment {

View File

@ -10,7 +10,7 @@ pub struct GiteaClient {
pub allow_insecure: bool, pub allow_insecure: bool,
} }
const APP_USER_AGENT: &'static str = const APP_USER_AGENT: &str =
concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),); concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),);
impl GiteaClient { impl GiteaClient {
@ -52,7 +52,7 @@ impl GiteaClient {
let request = client let request = client
.get(format!( .get(format!(
"{}/api/v1/repos/{}/{}", "{}/api/v1/repos/{}/{}",
&self.url.trim_end_matches("/"), &self.url.trim_end_matches('/'),
owner, owner,
repo repo
)) ))
@ -78,7 +78,7 @@ impl GiteaClient {
let request = client let request = client
.get(format!( .get(format!(
"{}/api/v1/repos/{}/{}/tags", "{}/api/v1/repos/{}/{}/tags",
&self.url.trim_end_matches("/"), &self.url.trim_end_matches('/'),
owner.into(), owner.into(),
repo.into() repo.into()
)) ))
@ -117,7 +117,7 @@ impl GiteaClient {
let request = client let request = client
.get(format!( .get(format!(
"{}/api/v1/repos/{}/{}/commits?page={}&limit={}&sha={}&stat=false&verification=false&files=false", "{}/api/v1/repos/{}/{}/commits?page={}&limit={}&sha={}&stat=false&verification=false&files=false",
&self.url.trim_end_matches("/"), &self.url.trim_end_matches('/'),
owner, owner,
repo, repo,
page, page,
@ -176,11 +176,9 @@ impl GiteaClient {
if let Some(since_sha) = &since_sha { if let Some(since_sha) = &since_sha {
if commit.sha.contains(since_sha) { if commit.sha.contains(since_sha) {
found_commit = true; found_commit = true;
} else { } else if !found_commit {
if !found_commit {
commits.push(commit); commits.push(commit);
} }
}
} else { } else {
commits.push(commit); commits.push(commit);
} }
@ -192,7 +190,7 @@ impl GiteaClient {
page += 1; page += 1;
} }
if found_commit == false && since_sha.is_some() { if !found_commit && since_sha.is_some() {
return Err(anyhow::anyhow!( return Err(anyhow::anyhow!(
"sha was not found in commit chain: {} on branch: {}", "sha was not found in commit chain: {} on branch: {}",
since_sha.unwrap_or("".into()), since_sha.unwrap_or("".into()),
@ -215,7 +213,7 @@ impl GiteaClient {
let request = client let request = client
.get(format!( .get(format!(
"{}/api/v1/repos/{}/{}/pulls?state=open&sort=recentupdate&page={}&limit={}", "{}/api/v1/repos/{}/{}/pulls?state=open&sort=recentupdate&page={}&limit={}",
&self.url.trim_end_matches("/"), &self.url.trim_end_matches('/'),
owner, owner,
repo, repo,
page, page,
@ -316,7 +314,7 @@ impl GiteaClient {
let request = client let request = client
.post(format!( .post(format!(
"{}/api/v1/repos/{}/{}/pulls", "{}/api/v1/repos/{}/{}/pulls",
&self.url.trim_end_matches("/"), &self.url.trim_end_matches('/'),
owner, owner,
repo, repo,
)) ))
@ -367,7 +365,7 @@ impl GiteaClient {
let request = client let request = client
.patch(format!( .patch(format!(
"{}/api/v1/repos/{}/{}/pulls/{}", "{}/api/v1/repos/{}/{}/pulls/{}",
&self.url.trim_end_matches("/"), &self.url.trim_end_matches('/'),
owner, owner,
repo, repo,
index index
@ -426,7 +424,7 @@ impl GiteaClient {
let request = client let request = client
.post(format!( .post(format!(
"{}/api/v1/repos/{}/{}/releases", "{}/api/v1/repos/{}/{}/releases",
&self.url.trim_end_matches("/"), &self.url.trim_end_matches('/'),
owner, owner,
repo, repo,
)) ))
@ -473,7 +471,7 @@ impl Commit {
pub fn get_title(&self) -> String { pub fn get_title(&self) -> String {
self.commit self.commit
.message .message
.split("\n") .split('\n')
.take(1) .take(1)
.collect::<Vec<&str>>() .collect::<Vec<&str>>()
.join("\n") .join("\n")

View File

@ -13,7 +13,7 @@ fn main() -> anyhow::Result<()> {
tracing_subscriber::fmt::init(); tracing_subscriber::fmt::init();
let current_dir = std::env::current_dir().ok(); let current_dir = std::env::current_dir().ok();
let current_dir = current_dir.as_ref().map(|p| p.as_path()); let current_dir = current_dir.as_deref();
Command::new().execute(current_dir)?; Command::new().execute(current_dir)?;

View File

@ -10,10 +10,11 @@ pub type DynUi = Box<dyn Ui + Send + Sync>;
impl Default for DynUi { impl Default for DynUi {
fn default() -> Self { fn default() -> Self {
Box::new(ConsoleUi::default()) Box::<ConsoleUi>::default()
} }
} }
#[derive(Default)]
pub(crate) struct ConsoleUi {} pub(crate) struct ConsoleUi {}
#[allow(dead_code)] #[allow(dead_code)]
@ -23,11 +24,7 @@ impl ConsoleUi {
} }
} }
impl Default for ConsoleUi {
fn default() -> Self {
Self {}
}
}
impl From<ConsoleUi> for DynUi { impl From<ConsoleUi> for DynUi {
fn from(value: ConsoleUi) -> Self { fn from(value: ConsoleUi) -> Self {

View File

@ -16,16 +16,14 @@ impl VersionIncrement {
C::Item: AsRef<str>, C::Item: AsRef<str>,
{ {
let mut commits = commits.into_iter().peekable(); let mut commits = commits.into_iter().peekable();
if commits.peek().is_none() { commits.peek()?;
return None;
}
if let Some(prerelease) = Self::is_prerelease(cur_version) { if let Some(prerelease) = Self::is_prerelease(cur_version) {
return Some(prerelease); return Some(prerelease);
} }
let commits: Vec<ConventionalCommit> = Self::parse_commits::<C>(commits); let commits: Vec<ConventionalCommit> = Self::parse_commits::<C>(commits);
return Some(Self::from_conventional_commits(commits)); Some(Self::from_conventional_commits(commits))
} }
#[inline] #[inline]
@ -71,8 +69,6 @@ mod tests {
use semver::Version; use semver::Version;
use tracing_test::traced_test; use tracing_test::traced_test;
#[test] #[test]
#[traced_test] #[traced_test]
fn is_prerelease() { fn is_prerelease() {
@ -186,6 +182,6 @@ mod tests {
let commits: Vec<&str> = Vec::new(); let commits: Vec<&str> = Vec::new();
let actual = VersionIncrement::from(&version, commits).is_none(); let actual = VersionIncrement::from(&version, commits).is_none();
assert_eq!(true, actual); assert!(actual);
} }
} }

View File

@ -40,7 +40,7 @@ impl NextVersion for Version {
VersionIncrement::Prerelease => Self { VersionIncrement::Prerelease => Self {
pre: { pre: {
let release = &self.pre; let release = &self.pre;
let release_version = match release.rsplit_once(".") { let release_version = match release.rsplit_once('.') {
Some((tag, version)) => match version.parse::<usize>() { Some((tag, version)) => match version.parse::<usize>() {
Ok(version) => format!("{tag}.{}", version + 1), Ok(version) => format!("{tag}.{}", version + 1),
Err(_) => format!("{tag}.1"), Err(_) => format!("{tag}.1"),

View File

@ -7,7 +7,7 @@ pub fn get_most_significant_version<'a>(tags: Vec<&'a Tag>) -> Option<&'a Tag> {
let mut versions: Vec<(&'a Tag, Version)> = tags let mut versions: Vec<(&'a Tag, Version)> = tags
.into_iter() .into_iter()
.filter_map(|c| { .filter_map(|c| {
if let Some(version) = c.name.trim_start_matches("v").parse::<Version>().ok() { if let Ok(version) = c.name.trim_start_matches('v').parse::<Version>() {
Some((c, version)) Some((c, version))
} else { } else {
None None

View File

@ -6,6 +6,7 @@ use std::{
sync::{Arc, Mutex}, sync::{Arc, Mutex},
}; };
#[derive(Default)]
struct BufferInner { struct BufferInner {
pub stdout: Vec<u8>, pub stdout: Vec<u8>,
pub stderr: Vec<u8>, pub stderr: Vec<u8>,
@ -84,14 +85,7 @@ impl Ui for BufferUi {
} }
} }
impl Default for BufferInner {
fn default() -> Self {
Self {
stdout: Vec::new(),
stderr: Vec::new(),
}
}
}
impl Default for BufferUi { impl Default for BufferUi {
fn default() -> Self { fn default() -> Self {

View File

@ -17,7 +17,7 @@ fn test_config_from_current_dir() {
let ui = &BufferUi::default(); let ui = &BufferUi::default();
let current_dir = get_test_data_path("cuddle-embed"); let current_dir = get_test_data_path("cuddle-embed");
Command::new_from_args(Some(ui), args.into_iter()) Command::new_from_args(Some(ui), args)
.execute(Some(&current_dir)) .execute(Some(&current_dir))
.unwrap(); .unwrap();
@ -33,7 +33,7 @@ fn test_config_from_source_dir() {
args.push("--source"); args.push("--source");
args.push(current_dir.to_str().unwrap()); args.push(current_dir.to_str().unwrap());
Command::new_from_args(Some(ui), args.into_iter()) Command::new_from_args(Some(ui), args)
.execute(None) .execute(None)
.unwrap(); .unwrap();
@ -50,7 +50,7 @@ fn test_config_from_stdin() {
args.push(current_dir.to_str().unwrap()); args.push(current_dir.to_str().unwrap());
args.push("--config-stdin"); args.push("--config-stdin");
Command::new_from_args_with_stdin(Some(ui), args.into_iter(), || Ok("please".into())) Command::new_from_args_with_stdin(Some(ui), args, || Ok("please".into()))
.execute(None) .execute(None)
.unwrap(); .unwrap();
@ -63,7 +63,7 @@ fn test_config_fails_when_not_path_is_set() {
let args = get_base_args(); let args = get_base_args();
let ui = &BufferUi::default(); let ui = &BufferUi::default();
let res = Command::new_from_args(Some(ui), args.into_iter()).execute(None); let res = Command::new_from_args(Some(ui), args).execute(None);
assert!(res.is_err()) assert!(res.is_err())
} }