From 64293cfe6c55fa1702b30b091d62e9b4b170f128 Mon Sep 17 00:00:00 2001 From: Paul Campbell Date: Mon, 25 Nov 2024 13:57:55 +0000 Subject: [PATCH] refactor: replace to_string uses with a macro --- crates/core/src/config/forge_config.rs | 7 +- crates/core/src/config/remote_url.rs | 4 +- crates/core/src/config/server.rs | 8 +- crates/core/src/config/server_repo_config.rs | 11 ++- crates/core/src/config/tests.rs | 21 ++--- .../src/config/webhook/forge_notification.rs | 8 +- crates/core/src/config/webhook/tests.rs | 8 +- crates/core/src/git/file.rs | 13 ++-- crates/core/src/git/git_ref.rs | 6 +- crates/core/src/git/repo_details.rs | 10 +-- crates/core/src/git/repository/factory.rs | 17 +++-- crates/core/src/git/repository/mod.rs | 15 ++-- crates/core/src/git/repository/open/oreal.rs | 33 ++++---- crates/core/src/git/repository/open/otest.rs | 7 +- .../core/src/git/repository/tests/factory.rs | 10 ++- crates/core/src/git/tests.rs | 76 +++++++++---------- crates/core/src/git/user_notification.rs | 2 +- crates/core/src/git/validation/positions.rs | 6 +- crates/core/src/git/validation/remotes.rs | 8 +- crates/core/src/git/validation/tests.rs | 8 +- crates/core/src/macros/mod.rs | 13 ++++ crates/core/src/macros/owned_string.rs | 9 +++ 22 files changed, 165 insertions(+), 135 deletions(-) create mode 100644 crates/core/src/macros/owned_string.rs diff --git a/crates/core/src/config/forge_config.rs b/crates/core/src/config/forge_config.rs index 7116be3..4f6c577 100644 --- a/crates/core/src/config/forge_config.rs +++ b/crates/core/src/config/forge_config.rs @@ -1,6 +1,9 @@ use std::collections::BTreeMap; -use crate::config::{ApiToken, ForgeType, Hostname, RepoAlias, ServerRepoConfig, User}; +use crate::{ + config::{ApiToken, ForgeType, Hostname, RepoAlias, ServerRepoConfig, User}, + s, +}; use super::CommitCount; @@ -18,7 +21,7 @@ use super::CommitCount; derive_more::Constructor, derive_more::Display, )] -#[display("{}:{}@{}", forge_type.to_string().to_lowercase(), user, hostname)] +#[display("{}:{}@{}", s!(forge_type).to_lowercase(), user, hostname)] pub struct ForgeConfig { forge_type: ForgeType, hostname: String, diff --git a/crates/core/src/config/remote_url.rs b/crates/core/src/config/remote_url.rs index d43ece6..f7624cd 100644 --- a/crates/core/src/config/remote_url.rs +++ b/crates/core/src/config/remote_url.rs @@ -1,7 +1,7 @@ // use std::borrow::ToOwned; -use crate::newtype; +use crate::{newtype, s}; newtype!( RemoteUrl, @@ -19,7 +19,7 @@ impl TryFrom for RemoteUrl { fn try_from(url: gix::Url) -> Result { let pass = url.password().map(ToOwned::to_owned); - let mut parsed = ::git_url_parse::GitUrl::parse(&url.to_string()).map_err(|_| ())?; + let mut parsed = ::git_url_parse::GitUrl::parse(&s!(url)).map_err(|_| ())?; parsed.token = pass; Ok(Self(parsed)) } diff --git a/crates/core/src/config/server.rs b/crates/core/src/config/server.rs index fbda868..786bd65 100644 --- a/crates/core/src/config/server.rs +++ b/crates/core/src/config/server.rs @@ -16,7 +16,7 @@ use tracing::info; use crate::{ config::{ForgeAlias, ForgeConfig, RepoAlias}, - newtype, + newtype, s, }; #[derive(Debug, thiserror::Error)] @@ -57,8 +57,8 @@ impl AppConfig { pub fn load(fs: &FileSystem) -> Result { let file = fs.base().join("git-next-server.toml"); info!(?file, ""); - let str = fs.file(&file).reader()?.to_string(); - Ok(toml::from_str(&str)?) + let str = fs.file(&file).reader()?; + Ok(toml::from_str(&s!(str))?) } pub fn forges(&self) -> impl Iterator { @@ -158,7 +158,7 @@ impl Display for RepoListenUrl { } impl From for ForgeWebhookUrl { fn from(value: RepoListenUrl) -> Self { - Self::new(value.to_string()) + Self::new(s!(value)) } } diff --git a/crates/core/src/config/server_repo_config.rs b/crates/core/src/config/server_repo_config.rs index 83013eb..6b93f90 100644 --- a/crates/core/src/config/server_repo_config.rs +++ b/crates/core/src/config/server_repo_config.rs @@ -1,9 +1,12 @@ // use std::path::PathBuf; -use crate::config::{ - git_dir::StoragePathType, BranchName, GitDir, RepoBranches, RepoConfig, RepoConfigSource, - RepoPath, +use crate::{ + config::{ + git_dir::StoragePathType, BranchName, GitDir, RepoBranches, RepoConfig, RepoConfigSource, + RepoPath, + }, + s, }; /// Defines a Repo within a `ForgeConfig` to be monitored by the server @@ -51,7 +54,7 @@ impl ServerRepoConfig { pub fn repo_config(&self) -> Option { match (&self.main, &self.next, &self.dev) { (Some(main), Some(next), Some(dev)) => Some(RepoConfig::new( - RepoBranches::new(main.to_string(), next.to_string(), dev.to_string()), + RepoBranches::new(s!(main), s!(next), s!(dev)), RepoConfigSource::Server, )), _ => None, diff --git a/crates/core/src/config/tests.rs b/crates/core/src/config/tests.rs index e67ee07..1cff9df 100644 --- a/crates/core/src/config/tests.rs +++ b/crates/core/src/config/tests.rs @@ -6,10 +6,11 @@ use secrecy::ExposeSecret; use std::collections::BTreeMap; use std::path::PathBuf; -use crate::server::AppConfig; -use crate::server::Http; -use crate::server::Storage; -use crate::webhook::push::Branch; +use crate::{ + s, + server::{AppConfig, Http, Storage}, + webhook::push::Branch, +}; mod url; @@ -445,7 +446,7 @@ mod forge_type { #[test] fn should_display_as_string() { - assert_eq!(ForgeType::MockForge.to_string(), "MockForge".to_string()); + assert_eq!(s!(ForgeType::MockForge), "MockForge"); } } mod gitdir { @@ -466,7 +467,7 @@ mod gitdir { let pathbuf = PathBuf::default().join("foo"); let gitdir = GitDir::new(pathbuf, git_dir::StoragePathType::Internal); - let result = gitdir.to_string(); + let result = s!(gitdir); assert_eq!(result, "foo"); } @@ -539,7 +540,7 @@ mod server { let shout_webhook_url = shout.webhook_url().unwrap_or_default(); let shout_webhook_secret = shout .webhook_secret() - .map(|secret| secret.expose_secret().to_string()) + .map(|secret| s!(secret.expose_secret())) .unwrap_or_default(); let_assert!(Some(shout_email) = shout.email()); let shout_email_from = shout_email.from(); @@ -560,7 +561,7 @@ mod server { let forge_type = forge_default.forge_type(); let forge_hostname = forge_default.hostname(); let forge_user = forge_default.user(); - let forge_token = forge_default.token().expose_secret().to_string(); + let forge_token = s!(forge_default.token().expose_secret()); let optional_max_dev_commits = forge_default .max_dev_commits() .map(CommitCount::peel) @@ -574,7 +575,7 @@ mod server { let gitdir = server_repo_config .gitdir() .map(|gitdir| gitdir.to_path_buf()) - .map(|pathbuf| pathbuf.display().to_string()) + .map(|pathbuf| s!(pathbuf.display())) .map(|gitdir| format!(r#", gitdir = "{gitdir}" "#)) .unwrap_or_default(); let repo_server_config = server_repo_config @@ -700,7 +701,7 @@ mod webhook { headers, given::a_webhook_message_body(), ); - assert_eq!(message.header(&key), Some(value)); + assert_eq!(message.header(&key), Some(value.as_str())); } } } diff --git a/crates/core/src/config/webhook/forge_notification.rs b/crates/core/src/config/webhook/forge_notification.rs index 35c748f..f66bbf4 100644 --- a/crates/core/src/config/webhook/forge_notification.rs +++ b/crates/core/src/config/webhook/forge_notification.rs @@ -1,9 +1,9 @@ // -use crate::config::{ForgeAlias, RepoAlias}; +use std::collections::BTreeMap; use derive_more::Constructor; -use std::{collections::BTreeMap, string::ToString}; +use crate::config::{ForgeAlias, RepoAlias}; /// A notification receive from a Forge, typically via a Webhook. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, derive_more::Constructor)] @@ -30,8 +30,8 @@ impl ForgeNotification { } #[must_use] - pub fn header(&self, header: &str) -> Option { - self.headers.get(header).map(ToString::to_string) + pub fn header(&self, header: &str) -> Option<&str> { + self.headers.get(header).map(std::string::String::as_str) } } diff --git a/crates/core/src/config/webhook/tests.rs b/crates/core/src/config/webhook/tests.rs index 0a597ee..dde11b8 100644 --- a/crates/core/src/config/webhook/tests.rs +++ b/crates/core/src/config/webhook/tests.rs @@ -1,11 +1,11 @@ mod auth { - use crate::WebhookAuth; + use crate::{s, WebhookAuth}; #[test] fn bytes() -> Result<(), Box> { let ulid = ulid::Ulid::new(); - let wa = WebhookAuth::try_new(ulid.to_string().as_str())?; + let wa = WebhookAuth::try_new(s!(ulid).as_str())?; assert_eq!(ulid.to_bytes(), wa.to_bytes()); @@ -16,9 +16,9 @@ mod auth { fn string() -> Result<(), Box> { let ulid = ulid::Ulid::new(); - let wa = WebhookAuth::try_new(ulid.to_string().as_str())?; + let wa = WebhookAuth::try_new(s!(ulid).as_str())?; - assert_eq!(ulid.to_string(), wa.to_string()); + assert_eq!(s!(ulid), s!(wa)); Ok(()) } diff --git a/crates/core/src/git/file.rs b/crates/core/src/git/file.rs index df5e796..7184cc6 100644 --- a/crates/core/src/git/file.rs +++ b/crates/core/src/git/file.rs @@ -53,29 +53,32 @@ pub enum Error { } mod gix_errors { - #![cfg(not(tarpaulin_include))] // third-party library errors + #![cfg(not(tarpaulin_include))] + use crate::s; + + // third-party library errors use super::Error; impl From for Error { fn from(value: gix::reference::find::existing::Error) -> Self { - Self::FindReference(value.to_string()) + Self::FindReference(s!(value)) } } impl From for Error { fn from(value: gix::object::commit::Error) -> Self { - Self::NoTreeInCommit(value.to_string()) + Self::NoTreeInCommit(s!(value)) } } impl From for Error { fn from(value: gix::object::find::existing::Error) -> Self { - Self::FindObject(value.to_string()) + Self::FindObject(s!(value)) } } impl From for Error { fn from(value: std::string::FromUtf8Error) -> Self { - Self::NonUtf8Blob(value.to_string()) + Self::NonUtf8Blob(s!(value)) } } } diff --git a/crates/core/src/git/git_ref.rs b/crates/core/src/git/git_ref.rs index 7548962..1e1a12d 100644 --- a/crates/core/src/git/git_ref.rs +++ b/crates/core/src/git/git_ref.rs @@ -1,5 +1,5 @@ // -use crate::newtype; +use crate::{newtype, s}; use derive_more::Display; @@ -8,11 +8,11 @@ use crate::git::{commit::Sha, Commit}; newtype!(GitRef, String, Display, "A git reference to a git commit."); impl From for GitRef { fn from(value: Commit) -> Self { - Self(value.sha().to_string()) + Self(s!(value.sha())) } } impl From for GitRef { fn from(value: Sha) -> Self { - Self(value.to_string()) + Self(s!(value)) } } diff --git a/crates/core/src/git/repo_details.rs b/crates/core/src/git/repo_details.rs index 1ae2326..fa6c4cd 100644 --- a/crates/core/src/git/repo_details.rs +++ b/crates/core/src/git/repo_details.rs @@ -5,7 +5,7 @@ use crate::{ repository::open::{oreal::RealOpenRepository, OpenRepositoryLike}, Generation, }, - pike, BranchName, ForgeAlias, ForgeConfig, ForgeDetails, GitDir, Hostname, RemoteUrl, + pike, s, BranchName, ForgeAlias, ForgeConfig, ForgeDetails, GitDir, Hostname, RemoteUrl, RepoAlias, RepoConfig, RepoPath, ServerRepoConfig, StoragePathType, }; @@ -143,7 +143,7 @@ impl RepoDetails { // load config file let config_filename = &self.gitdir.join("config"); let file = fs.file(config_filename); - let config_file = file.reader()?.to_string(); + let config_file = file.reader()?; let mut config_lines = config_file .lines() .map(ToOwned::to_owned) @@ -152,7 +152,7 @@ impl RepoDetails { let url_line = format!(r#" url = "{url}""#); if config_lines .iter() - .any(|line| *line == r#"[remote "origin"]"#) + .any(|line| line == r#"[remote "origin"]"#) { tracing::debug!("has an 'origin' remote"); config_lines @@ -161,12 +161,12 @@ impl RepoDetails { .for_each(|line| line.clone_from(&url_line)); } else { tracing::debug!("has no 'origin' remote"); - config_lines.push(r#"[remote "origin"]"#.to_owned()); + config_lines.push(s!(r#"[remote "origin"]"#)); config_lines.push(url_line); } tracing::debug!(?config_lines, "updated file"); // write config file back out - file.write(config_lines.join("\n").as_str())?; + file.write(config_lines.join("\n"))?; Ok(()) } } diff --git a/crates/core/src/git/repository/factory.rs b/crates/core/src/git/repository/factory.rs index c9e6dcb..357a03a 100644 --- a/crates/core/src/git/repository/factory.rs +++ b/crates/core/src/git/repository/factory.rs @@ -1,11 +1,14 @@ // -use crate::git::{ - self, - repository::{ - open::{oreal::RealOpenRepository, OpenRepositoryLike}, - Direction, Result, +use crate::{ + git::{ + self, + repository::{ + open::{oreal::RealOpenRepository, OpenRepositoryLike}, + Direction, Result, + }, + RepoDetails, }, - RepoDetails, + s, }; use secrecy::ExposeSecret as _; @@ -51,7 +54,7 @@ impl RepositoryFactory for RealRepositoryFactory { fn open(&self, repo_details: &RepoDetails) -> Result> { let repo = repo_details .open() - .map_err(|e| git::repository::Error::Open(e.to_string()))?; + .map_err(|e| git::repository::Error::Open(s!(e)))?; let found = repo.find_default_remote(Direction::Fetch); repo_details.assert_remote_url(found)?; diff --git a/crates/core/src/git/repository/mod.rs b/crates/core/src/git/repository/mod.rs index c93ab81..399eecd 100644 --- a/crates/core/src/git/repository/mod.rs +++ b/crates/core/src/git/repository/mod.rs @@ -46,6 +46,8 @@ pub fn open( repository_factory: &dyn factory::RepositoryFactory, repo_details: &RepoDetails, ) -> Result> { + use crate::s; + let open_repository = if repo_details.gitdir.exists() { info!("Local copy found - opening..."); let repo = repository_factory.open(repo_details)?; @@ -57,7 +59,7 @@ pub fn open( }; info!("Validating..."); validate_default_remotes(&*open_repository, repo_details) - .map_err(|e| Error::Validation(e.to_string()))?; + .map_err(|e| Error::Validation(s!(e)))?; Ok(open_repository) } @@ -140,21 +142,24 @@ pub enum Error { } mod gix_errors { - #![cfg(not(tarpaulin_include))] // third-party library errors + #![cfg(not(tarpaulin_include))] + use crate::s; + + // third-party library errors use super::Error; impl From for Error { fn from(value: gix::clone::Error) -> Self { - Self::Clone(value.to_string()) + Self::Clone(s!(value)) } } impl From for Error { fn from(value: gix::open::Error) -> Self { - Self::Open(value.to_string()) + Self::Open(s!(value)) } } impl From for Error { fn from(value: gix::clone::fetch::Error) -> Self { - Self::Fetch(value.to_string()) + Self::Fetch(s!(value)) } } } diff --git a/crates/core/src/git/repository/open/oreal.rs b/crates/core/src/git/repository/open/oreal.rs index 97b3a76..691e7d8 100644 --- a/crates/core/src/git/repository/open/oreal.rs +++ b/crates/core/src/git/repository/open/oreal.rs @@ -1,7 +1,7 @@ // use crate::{ git::{self, repository::OpenRepositoryLike}, - BranchName, ForgeDetails, Hostname, RemoteUrl, RepoPath, + s, BranchName, ForgeDetails, Hostname, RemoteUrl, RepoPath, }; use derive_more::Constructor; @@ -31,7 +31,7 @@ impl super::OpenRepositoryLike for RealOpenRepository { Ok(refs.remote_branches().map(|rb| { rb.filter_map(Result::ok) .map(|r| r.name().to_owned()) - .map(|n| n.to_string()) + .map(|n| s!(n)) .filter_map(|p| { p.strip_prefix("refs/remotes/origin/") .map(ToOwned::to_owned) @@ -157,39 +157,38 @@ impl super::OpenRepositoryLike for RealOpenRepository { let thread_local = repo.to_thread_local(); let branch_head = thread_local .rev_parse_single(branch) - .map_err(|e| e.to_string()) + .map_err(|e| s!(e)) .map_err(as_gix_error(branch_name.clone()))?; let object = branch_head .object() - .map_err(|e| e.to_string()) + .map_err(|e| s!(e)) .map_err(as_gix_error(branch_name.clone()))?; let commit = object .try_into_commit() - .map_err(|e| e.to_string()) + .map_err(|e| s!(e)) .map_err(as_gix_error(branch_name.clone()))?; let walk = thread_local .rev_walk([commit.id]) .all() - .map_err(|e| e.to_string()) + .map_err(|e| s!(e)) .map_err(as_gix_error(branch_name.clone()))?; let mut commits = vec![]; for item in walk.take(limit) { let item = item - .map_err(|e| e.to_string()) + .map_err(|e| s!(e)) .map_err(as_gix_error(branch_name.clone()))?; let commit = item .object() - .map_err(|e| e.to_string()) + .map_err(|e| s!(e)) .map_err(as_gix_error(branch_name.clone()))?; - let id = commit.id().to_string(); + let id = commit.id(); let message = commit .message_raw() - .map_err(|e| e.to_string()) - .map_err(as_gix_error(branch_name.clone()))? - .to_string(); + .map_err(|e| s!(e)) + .map_err(as_gix_error(branch_name.clone()))?; let commit = git::Commit::new( - git::commit::Sha::new(id), - git::commit::Message::new(message), + git::commit::Sha::new(s!(id)), + git::commit::Message::new(s!(message)), ); if find_commits.contains(&commit) { commits.push(commit); @@ -215,7 +214,7 @@ impl super::OpenRepositoryLike for RealOpenRepository { let commit = obj.into_commit(); let tree = commit.tree()?; let ent = tree - .find_entry(file_name.to_string_lossy().to_string()) + .find_entry(s!(file_name.to_string_lossy())) .ok_or(git::file::Error::FileNotFound)?; let fobj = ent.object()?; let blob = fobj.into_blob().take_data(); @@ -236,9 +235,9 @@ fn as_gix_error(branch: BranchName) -> impl FnOnce(String) -> git::commit::log:: impl From<&RemoteUrl> for git::GitRemote { fn from(url: &RemoteUrl) -> Self { let host = url.host.clone().unwrap_or_default(); - let path = url.path.to_string(); + let path = s!(url.path); let path = path.strip_prefix('/').map_or(path.as_str(), |path| path); let path = path.strip_suffix(".git").map_or(path, |path| path); - Self::new(Hostname::new(host), RepoPath::new(path.to_string())) + Self::new(Hostname::new(host), RepoPath::new(s!(path))) } } diff --git a/crates/core/src/git/repository/open/otest.rs b/crates/core/src/git/repository/open/otest.rs index 6fb325f..556f044 100644 --- a/crates/core/src/git/repository/open/otest.rs +++ b/crates/core/src/git/repository/open/otest.rs @@ -4,7 +4,7 @@ use crate::{ self, repository::open::{OpenRepositoryLike, RealOpenRepository}, }, - BranchName, ForgeDetails, GitDir, RemoteUrl, RepoBranches, + s, BranchName, ForgeDetails, GitDir, RemoteUrl, RepoBranches, }; use derive_more::Constructor; @@ -174,10 +174,7 @@ impl TestOpenRepository { let config_file = fs.base().join(gitdir.to_path_buf()).join(".git/config"); let file = fs.file(&config_file); #[allow(clippy::expect_used)] - let contents = file - .reader() - .expect("read original .git/config") - .to_string(); + let contents = s!(file.reader().expect("read original .git/config")); let updated_contents = format!( r#"{contents} [remote "origin"] diff --git a/crates/core/src/git/repository/tests/factory.rs b/crates/core/src/git/repository/tests/factory.rs index b7b7a63..b85032d 100644 --- a/crates/core/src/git/repository/tests/factory.rs +++ b/crates/core/src/git/repository/tests/factory.rs @@ -1,3 +1,5 @@ +use crate::s; + // use super::*; @@ -23,7 +25,7 @@ fn open_where_storage_external_auth_matches() -> TestResult { tracing::debug!(?result, "open"); assert!(result.is_ok()); // verify origin in .git/config matches url - let config = fs.file(&fs.base().join("config")).reader()?.to_string(); + let config = s!(fs.file(&fs.base().join("config")).reader()?); tracing::debug!(config=?config.lines().collect::>(), "auth"); assert!(config.lines().any(|line| line.contains(url))); Ok(()) @@ -60,7 +62,7 @@ fn open_where_storage_external_auth_differs_error() -> TestResult { )); // verify origin in .git/config is unchanged - let config = fs.file(&fs.base().join("config")).reader()?.to_string(); + let config = s!(fs.file(&fs.base().join("config")).reader()?); tracing::debug!(config=?config.lines().collect::>(), "auth"); assert!(config.lines().any(|line| line.contains(original_url))); // the original urk Ok(()) @@ -86,7 +88,7 @@ fn open_where_storage_internal_auth_matches() -> TestResult { tracing::debug!(?result, "open"); assert!(result.is_ok()); // verify origin in .git/config matches url - let config = fs.file(&fs.base().join("config")).reader()?.to_string(); + let config = s!(fs.file(&fs.base().join("config")).reader()?); tracing::debug!(config=?config.lines().collect::>(), "auth"); assert!( config.lines().any(|line| line.contains(url)), @@ -121,7 +123,7 @@ fn open_where_storage_internal_auth_differs_update_config() -> TestResult { assert!(result.is_ok()); // verify origin in .git/config is unchanged - let config = fs.file(&fs.base().join("config")).reader()?.to_string(); + let config = s!(fs.file(&fs.base().join("config")).reader()?); tracing::debug!(config=?config.lines().collect::>(), "auth"); assert!( config diff --git a/crates/core/src/git/tests.rs b/crates/core/src/git/tests.rs index 1ec296d..7c6b237 100644 --- a/crates/core/src/git/tests.rs +++ b/crates/core/src/git/tests.rs @@ -2,7 +2,7 @@ use crate::{ git::{self, Generation, GitRef, GitRemote, RepoDetails}, git_dir::StoragePathType, - webhook, BranchName, ForgeAlias, ForgeConfig, ForgeType, GitDir, Hostname, RemoteUrl, + s, webhook, BranchName, ForgeAlias, ForgeConfig, ForgeType, GitDir, Hostname, RemoteUrl, RepoAlias, RepoBranches, RepoConfig, RepoConfigSource, RepoPath, ServerRepoConfig, }; @@ -17,6 +17,7 @@ use std::{ type TestResult = Result<(), Box>; mod commit { + use super::*; #[test] @@ -41,24 +42,25 @@ mod commit { let commit = git::Commit::from(push); let expected = git::Commit::new( - git::commit::Sha::new(sha.to_string()), - git::commit::Message::new(message.to_string()), + git::commit::Sha::new(sha), + git::commit::Message::new(message), ); assert_eq!(commit, expected); } } mod generation { + use super::*; #[test] fn should_increment() { let mut g = Generation::default(); - assert_eq!(g.to_string(), "0"); + assert_eq!(s!(g), "0"); g.inc(); - assert_eq!(g.to_string(), "1"); + assert_eq!(s!(g), "1"); } } mod gitref { @@ -67,12 +69,12 @@ mod gitref { #[test] fn should_convert_from_commit() { let commit = git::Commit::new( - git::commit::Sha::new("sha".to_string()), - git::commit::Message::new("message".to_string()), + git::commit::Sha::new("sha"), + git::commit::Message::new("message"), ); let gitref = GitRef::from(commit); - assert_eq!(gitref.to_string(), "sha"); + assert_eq!(s!(gitref), "sha"); } } mod gitremote { @@ -81,16 +83,16 @@ mod gitremote { #[test] fn should_return_hostname() { - let host = Hostname::new("localhost".to_string()); - let repo_path = RepoPath::new("kemitix/git-next".to_string()); + let host = Hostname::new("localhost"); + let repo_path = RepoPath::new(s!("kemitix/git-next")); let gr = GitRemote::new(host.clone(), repo_path); assert_eq!(gr.host(), &host); } #[test] fn should_return_repo_path() { - let host = Hostname::new("localhost".to_string()); - let repo_path = RepoPath::new("kemitix/git-next".to_string()); + let host = Hostname::new("localhost"); + let repo_path = RepoPath::new(s!("kemitix/git-next")); let gr = GitRemote::new(host, repo_path.clone()); assert_eq!(gr.repo_path(), &repo_path); @@ -101,7 +103,7 @@ mod push { #[test] fn force_no_should_display() { - assert_eq!(git::push::Force::No.to_string(), "fast-forward"); + assert_eq!(s!(git::push::Force::No), "fast-forward"); } #[test] @@ -109,7 +111,7 @@ mod push { let sha = given::a_name(); let commit = given::a_commit_with_sha(&git::commit::Sha::new(sha.clone())); assert_eq!( - git::push::Force::From(GitRef::from(commit)).to_string(), + s!(git::push::Force::From(GitRef::from(commit))), format!("force-if-from:{sha}") ); } @@ -158,20 +160,13 @@ mod repo_details { let rd = RepoDetails::new( Generation::default(), &RepoAlias::new("foo"), - &ServerRepoConfig::new( - "repo".to_string(), - "branch".to_string(), - None, - None, - None, - None, - ), - &ForgeAlias::new("default".to_string()), + &ServerRepoConfig::new(s!("repo"), s!("branch"), None, None, None, None), + &ForgeAlias::new("default"), &ForgeConfig::new( ForgeType::MockForge, - "host".to_string(), - "user".to_string(), - "token".to_string(), + s!("host"), + s!("user"), + s!("token"), given::maybe_a_number(), // max dev commits BTreeMap::new(), ), @@ -303,7 +298,7 @@ pub mod given { pub fn a_webhook_push(sha: &git::commit::Sha, message: &git::commit::Message) -> webhook::Push { let branch = a_branch_name(); - webhook::Push::new(branch, sha.to_string(), message.to_string()) + webhook::Push::new(branch, s!(sha), s!(message)) } pub fn a_filesystem() -> kxio::fs::TempFileSystem { @@ -338,7 +333,7 @@ pub mod given { repo.persist(); // load config file let file = fs.file(&path.join("config")); - let config_file = file.reader().unwrap().to_string(); + let config_file = file.reader().unwrap(); // add use are origin url let mut config_lines = config_file.lines().collect::>(); config_lines.push(r#"[remote "origin"]"#); @@ -417,12 +412,12 @@ pub mod then { .join(gitdir.to_path_buf()) .join(".git") .join("refs"); - let local_branch = gitrefs.join("heads").join(branch_name.to_string().as_str()); + let local_branch = gitrefs.join("heads").join(branch_name.as_str()); let origin_heads = gitrefs.join("remotes").join("origin"); - let remote_branch = origin_heads.join(branch_name.to_string().as_str()); - let contents = fs.file(&local_branch).reader()?.to_string(); + let remote_branch = origin_heads.join(branch_name.as_str()); + let contents = fs.file(&local_branch).reader()?; fs.dir(&origin_heads).create_all()?; - fs.file(&remote_branch).write(&contents)?; + fs.file(&remote_branch).write(s!(contents))?; Ok(()) } @@ -431,7 +426,7 @@ pub mod then { &format!("git checkout -b {branch_name}"), std::process::Command::new("/usr/bin/git") .current_dir(gitdir.to_path_buf()) - .args(["checkout", "-b", branch_name.to_string().as_str()]) + .args(["checkout", "-b", branch_name.as_str()]) .output(), )?; Ok(()) @@ -442,7 +437,7 @@ pub mod then { &format!("git switch {branch_name}"), std::process::Command::new("/usr/bin/git") .current_dir(gitdir.to_path_buf()) - .args(["switch", branch_name.to_string().as_str()]) + .args(["switch", branch_name.as_str()]) .output(), ) } @@ -474,7 +469,7 @@ pub mod then { &format!("git add {file:?}"), std::process::Command::new("/usr/bin/git") .current_dir(gitdir.to_path_buf()) - .args(["add", file.display().to_string().as_str()]) + .args(["add", s!(file.display()).as_str()]) .output(), ) } @@ -484,10 +479,7 @@ pub mod then { &format!(r#"git commit -m"Added {file:?}""#), std::process::Command::new("/usr/bin/git") .current_dir(gitdir.to_path_buf()) - .args([ - "commit", - format!(r#"-m"Added {}"#, file.display().to_string().as_str()).as_str(), - ]) + .args(["commit", format!(r#"-m"Added {}"#, file.display()).as_str()]) .output(), ) } @@ -513,8 +505,8 @@ pub mod then { .join(".git") .join("refs") .join("heads") - .join(branch_name.to_string().as_str()); - let sha = fs.file(&main_ref).reader()?.to_string(); - Ok(git::commit::Sha::new(sha.trim().to_string())) + .join(branch_name.as_str()); + let sha = fs.file(&main_ref).reader()?; + Ok(git::commit::Sha::new(s!(sha).trim())) } } diff --git a/crates/core/src/git/user_notification.rs b/crates/core/src/git/user_notification.rs index cb29c66..6095009 100644 --- a/crates/core/src/git/user_notification.rs +++ b/crates/core/src/git/user_notification.rs @@ -37,7 +37,7 @@ pub enum UserNotification { impl UserNotification { #[must_use] pub fn as_json(&self, timestamp: time::OffsetDateTime) -> serde_json::Value { - let timestamp = timestamp.unix_timestamp().to_string(); + let timestamp = timestamp.unix_timestamp(); match self { Self::CICheckFailed { forge_alias, diff --git a/crates/core/src/git/validation/positions.rs b/crates/core/src/git/validation/positions.rs index 3c3411c..85c2ef9 100644 --- a/crates/core/src/git/validation/positions.rs +++ b/crates/core/src/git/validation/positions.rs @@ -1,7 +1,7 @@ // use crate::{ git::{self, repository::open::OpenRepositoryLike, RepoDetails, UserNotification}, - BranchName, RepoConfig, + s, BranchName, RepoConfig, }; use tracing::{debug, instrument}; @@ -179,11 +179,11 @@ pub enum Error { } impl From for Error { fn from(value: git::fetch::Error) -> Self { - Self::Retryable(value.to_string()) + Self::Retryable(s!(value)) } } impl From for Error { fn from(value: git::commit::log::Error) -> Self { - Self::Retryable(value.to_string()) + Self::Retryable(s!(value)) } } diff --git a/crates/core/src/git/validation/remotes.rs b/crates/core/src/git/validation/remotes.rs index 2b5fa20..bf76d72 100644 --- a/crates/core/src/git/validation/remotes.rs +++ b/crates/core/src/git/validation/remotes.rs @@ -1,7 +1,7 @@ // use crate::{ git::{self, repository::open::OpenRepositoryLike}, - RemoteUrl, + s, RemoteUrl, }; use tracing::info; @@ -18,9 +18,9 @@ pub fn validate_default_remotes( .find_default_remote(git::repository::Direction::Fetch) .ok_or(Error::NoDefaultFetchRemote)?; let Some(remote_url) = repo_details.remote_url() else { - return Err(git::validation::remotes::Error::UnableToOpenRepo( - "Unable to build forge url".to_string(), - )); + return Err(git::validation::remotes::Error::UnableToOpenRepo(s!( + "Unable to build forge url" + ))); }; info!(config = %remote_url, push = %push_remote, fetch = %fetch_remote, "Check remotes match"); if !remote_url.matches(&push_remote) { diff --git a/crates/core/src/git/validation/tests.rs b/crates/core/src/git/validation/tests.rs index 4e54851..05a8ea8 100644 --- a/crates/core/src/git/validation/tests.rs +++ b/crates/core/src/git/validation/tests.rs @@ -10,7 +10,7 @@ use crate::{ tests::{given, then}, validation::positions::validate, }, - GitDir, StoragePathType, + s, GitDir, StoragePathType, }; use assert2::let_assert; @@ -102,7 +102,7 @@ mod positions { if branch_name == &main_branch { Err(git::commit::log::Error::Gix { branch: branch_name.clone(), - error: "foo".to_string(), + error: s!("foo"), }) } else { Ok(vec![]) @@ -141,7 +141,7 @@ mod positions { if branch_name == &next_branch { Err(git::commit::log::Error::Gix { branch: branch_name.clone(), - error: "foo".to_string(), + error: s!("foo"), }) } else { Ok(vec![given::a_commit()]) @@ -180,7 +180,7 @@ mod positions { if branch_name == &dev_branch { Err(git::commit::log::Error::Gix { branch: branch_name.clone(), - error: "foo".to_string(), + error: s!("foo"), }) } else { Ok(vec![given::a_commit()]) diff --git a/crates/core/src/macros/mod.rs b/crates/core/src/macros/mod.rs index 23efb2a..270ca66 100644 --- a/crates/core/src/macros/mod.rs +++ b/crates/core/src/macros/mod.rs @@ -1,2 +1,15 @@ mod message; mod newtype; +mod owned_string; + +#[cfg(test)] +mod tests { + use crate::s; + + #[test] + fn macro_s_to_string() { + let s: String = s!("this"); + + assert_eq!(s, "this"); + } +} diff --git a/crates/core/src/macros/owned_string.rs b/crates/core/src/macros/owned_string.rs new file mode 100644 index 0000000..664e5ef --- /dev/null +++ b/crates/core/src/macros/owned_string.rs @@ -0,0 +1,9 @@ +// + +/// Converts the value into a [String] by calling the `std::fmt::Display::to_string` on the value. +#[macro_export] +macro_rules! s { + ($value:expr) => { + $value.to_string() + }; +}