refactor: replace to_string uses with a macro
All checks were successful
ci/woodpecker/push/cron-docker-builder Pipeline was successful
Rust / build (map[name:stable]) (push) Successful in 8m8s
ci/woodpecker/push/push-next Pipeline was successful
ci/woodpecker/push/tag-created Pipeline was successful
Rust / build (map[name:nightly]) (push) Successful in 13m25s
Release Please / Release-plz (push) Successful in 5m54s
ci/woodpecker/cron/cron-docker-builder Pipeline was successful
ci/woodpecker/cron/push-next Pipeline was successful
ci/woodpecker/cron/tag-created Pipeline was successful

This commit is contained in:
Paul Campbell 2024-11-25 13:57:55 +00:00
parent 6872483841
commit 64293cfe6c
22 changed files with 165 additions and 135 deletions

View file

@ -1,6 +1,9 @@
use std::collections::BTreeMap; 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; use super::CommitCount;
@ -18,7 +21,7 @@ use super::CommitCount;
derive_more::Constructor, derive_more::Constructor,
derive_more::Display, derive_more::Display,
)] )]
#[display("{}:{}@{}", forge_type.to_string().to_lowercase(), user, hostname)] #[display("{}:{}@{}", s!(forge_type).to_lowercase(), user, hostname)]
pub struct ForgeConfig { pub struct ForgeConfig {
forge_type: ForgeType, forge_type: ForgeType,
hostname: String, hostname: String,

View file

@ -1,7 +1,7 @@
// //
use std::borrow::ToOwned; use std::borrow::ToOwned;
use crate::newtype; use crate::{newtype, s};
newtype!( newtype!(
RemoteUrl, RemoteUrl,
@ -19,7 +19,7 @@ impl TryFrom<gix::Url> for RemoteUrl {
fn try_from(url: gix::Url) -> Result<Self, Self::Error> { fn try_from(url: gix::Url) -> Result<Self, Self::Error> {
let pass = url.password().map(ToOwned::to_owned); 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; parsed.token = pass;
Ok(Self(parsed)) Ok(Self(parsed))
} }

View file

@ -16,7 +16,7 @@ use tracing::info;
use crate::{ use crate::{
config::{ForgeAlias, ForgeConfig, RepoAlias}, config::{ForgeAlias, ForgeConfig, RepoAlias},
newtype, newtype, s,
}; };
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
@ -57,8 +57,8 @@ impl AppConfig {
pub fn load(fs: &FileSystem) -> Result<Self> { pub fn load(fs: &FileSystem) -> Result<Self> {
let file = fs.base().join("git-next-server.toml"); let file = fs.base().join("git-next-server.toml");
info!(?file, ""); info!(?file, "");
let str = fs.file(&file).reader()?.to_string(); let str = fs.file(&file).reader()?;
Ok(toml::from_str(&str)?) Ok(toml::from_str(&s!(str))?)
} }
pub fn forges(&self) -> impl Iterator<Item = (ForgeAlias, &ForgeConfig)> { pub fn forges(&self) -> impl Iterator<Item = (ForgeAlias, &ForgeConfig)> {
@ -158,7 +158,7 @@ impl Display for RepoListenUrl {
} }
impl From<RepoListenUrl> for ForgeWebhookUrl { impl From<RepoListenUrl> for ForgeWebhookUrl {
fn from(value: RepoListenUrl) -> Self { fn from(value: RepoListenUrl) -> Self {
Self::new(value.to_string()) Self::new(s!(value))
} }
} }

View file

@ -1,9 +1,12 @@
// //
use std::path::PathBuf; use std::path::PathBuf;
use crate::config::{ use crate::{
git_dir::StoragePathType, BranchName, GitDir, RepoBranches, RepoConfig, RepoConfigSource, config::{
RepoPath, git_dir::StoragePathType, BranchName, GitDir, RepoBranches, RepoConfig, RepoConfigSource,
RepoPath,
},
s,
}; };
/// Defines a Repo within a `ForgeConfig` to be monitored by the server /// Defines a Repo within a `ForgeConfig` to be monitored by the server
@ -51,7 +54,7 @@ impl ServerRepoConfig {
pub fn repo_config(&self) -> Option<RepoConfig> { pub fn repo_config(&self) -> Option<RepoConfig> {
match (&self.main, &self.next, &self.dev) { match (&self.main, &self.next, &self.dev) {
(Some(main), Some(next), Some(dev)) => Some(RepoConfig::new( (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, RepoConfigSource::Server,
)), )),
_ => None, _ => None,

View file

@ -6,10 +6,11 @@ use secrecy::ExposeSecret;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::path::PathBuf; use std::path::PathBuf;
use crate::server::AppConfig; use crate::{
use crate::server::Http; s,
use crate::server::Storage; server::{AppConfig, Http, Storage},
use crate::webhook::push::Branch; webhook::push::Branch,
};
mod url; mod url;
@ -445,7 +446,7 @@ mod forge_type {
#[test] #[test]
fn should_display_as_string() { fn should_display_as_string() {
assert_eq!(ForgeType::MockForge.to_string(), "MockForge".to_string()); assert_eq!(s!(ForgeType::MockForge), "MockForge");
} }
} }
mod gitdir { mod gitdir {
@ -466,7 +467,7 @@ mod gitdir {
let pathbuf = PathBuf::default().join("foo"); let pathbuf = PathBuf::default().join("foo");
let gitdir = GitDir::new(pathbuf, git_dir::StoragePathType::Internal); let gitdir = GitDir::new(pathbuf, git_dir::StoragePathType::Internal);
let result = gitdir.to_string(); let result = s!(gitdir);
assert_eq!(result, "foo"); assert_eq!(result, "foo");
} }
@ -539,7 +540,7 @@ mod server {
let shout_webhook_url = shout.webhook_url().unwrap_or_default(); let shout_webhook_url = shout.webhook_url().unwrap_or_default();
let shout_webhook_secret = shout let shout_webhook_secret = shout
.webhook_secret() .webhook_secret()
.map(|secret| secret.expose_secret().to_string()) .map(|secret| s!(secret.expose_secret()))
.unwrap_or_default(); .unwrap_or_default();
let_assert!(Some(shout_email) = shout.email()); let_assert!(Some(shout_email) = shout.email());
let shout_email_from = shout_email.from(); let shout_email_from = shout_email.from();
@ -560,7 +561,7 @@ mod server {
let forge_type = forge_default.forge_type(); let forge_type = forge_default.forge_type();
let forge_hostname = forge_default.hostname(); let forge_hostname = forge_default.hostname();
let forge_user = forge_default.user(); 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 let optional_max_dev_commits = forge_default
.max_dev_commits() .max_dev_commits()
.map(CommitCount::peel) .map(CommitCount::peel)
@ -574,7 +575,7 @@ mod server {
let gitdir = server_repo_config let gitdir = server_repo_config
.gitdir() .gitdir()
.map(|gitdir| gitdir.to_path_buf()) .map(|gitdir| gitdir.to_path_buf())
.map(|pathbuf| pathbuf.display().to_string()) .map(|pathbuf| s!(pathbuf.display()))
.map(|gitdir| format!(r#", gitdir = "{gitdir}" "#)) .map(|gitdir| format!(r#", gitdir = "{gitdir}" "#))
.unwrap_or_default(); .unwrap_or_default();
let repo_server_config = server_repo_config let repo_server_config = server_repo_config
@ -700,7 +701,7 @@ mod webhook {
headers, headers,
given::a_webhook_message_body(), given::a_webhook_message_body(),
); );
assert_eq!(message.header(&key), Some(value)); assert_eq!(message.header(&key), Some(value.as_str()));
} }
} }
} }

View file

@ -1,9 +1,9 @@
// //
use crate::config::{ForgeAlias, RepoAlias}; use std::collections::BTreeMap;
use derive_more::Constructor; 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. /// A notification receive from a Forge, typically via a Webhook.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, derive_more::Constructor)] #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, derive_more::Constructor)]
@ -30,8 +30,8 @@ impl ForgeNotification {
} }
#[must_use] #[must_use]
pub fn header(&self, header: &str) -> Option<String> { pub fn header(&self, header: &str) -> Option<&str> {
self.headers.get(header).map(ToString::to_string) self.headers.get(header).map(std::string::String::as_str)
} }
} }

View file

@ -1,11 +1,11 @@
mod auth { mod auth {
use crate::WebhookAuth; use crate::{s, WebhookAuth};
#[test] #[test]
fn bytes() -> Result<(), Box<dyn std::error::Error>> { fn bytes() -> Result<(), Box<dyn std::error::Error>> {
let ulid = ulid::Ulid::new(); 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()); assert_eq!(ulid.to_bytes(), wa.to_bytes());
@ -16,9 +16,9 @@ mod auth {
fn string() -> Result<(), Box<dyn std::error::Error>> { fn string() -> Result<(), Box<dyn std::error::Error>> {
let ulid = ulid::Ulid::new(); 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(()) Ok(())
} }

View file

@ -53,29 +53,32 @@ pub enum Error {
} }
mod gix_errors { 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; use super::Error;
impl From<gix::reference::find::existing::Error> for Error { impl From<gix::reference::find::existing::Error> for Error {
fn from(value: gix::reference::find::existing::Error) -> Self { fn from(value: gix::reference::find::existing::Error) -> Self {
Self::FindReference(value.to_string()) Self::FindReference(s!(value))
} }
} }
impl From<gix::object::commit::Error> for Error { impl From<gix::object::commit::Error> for Error {
fn from(value: gix::object::commit::Error) -> Self { fn from(value: gix::object::commit::Error) -> Self {
Self::NoTreeInCommit(value.to_string()) Self::NoTreeInCommit(s!(value))
} }
} }
impl From<gix::object::find::existing::Error> for Error { impl From<gix::object::find::existing::Error> for Error {
fn from(value: gix::object::find::existing::Error) -> Self { fn from(value: gix::object::find::existing::Error) -> Self {
Self::FindObject(value.to_string()) Self::FindObject(s!(value))
} }
} }
impl From<std::string::FromUtf8Error> for Error { impl From<std::string::FromUtf8Error> for Error {
fn from(value: std::string::FromUtf8Error) -> Self { fn from(value: std::string::FromUtf8Error) -> Self {
Self::NonUtf8Blob(value.to_string()) Self::NonUtf8Blob(s!(value))
} }
} }
} }

View file

@ -1,5 +1,5 @@
// //
use crate::newtype; use crate::{newtype, s};
use derive_more::Display; 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."); newtype!(GitRef, String, Display, "A git reference to a git commit.");
impl From<Commit> for GitRef { impl From<Commit> for GitRef {
fn from(value: Commit) -> Self { fn from(value: Commit) -> Self {
Self(value.sha().to_string()) Self(s!(value.sha()))
} }
} }
impl From<Sha> for GitRef { impl From<Sha> for GitRef {
fn from(value: Sha) -> Self { fn from(value: Sha) -> Self {
Self(value.to_string()) Self(s!(value))
} }
} }

View file

@ -5,7 +5,7 @@ use crate::{
repository::open::{oreal::RealOpenRepository, OpenRepositoryLike}, repository::open::{oreal::RealOpenRepository, OpenRepositoryLike},
Generation, Generation,
}, },
pike, BranchName, ForgeAlias, ForgeConfig, ForgeDetails, GitDir, Hostname, RemoteUrl, pike, s, BranchName, ForgeAlias, ForgeConfig, ForgeDetails, GitDir, Hostname, RemoteUrl,
RepoAlias, RepoConfig, RepoPath, ServerRepoConfig, StoragePathType, RepoAlias, RepoConfig, RepoPath, ServerRepoConfig, StoragePathType,
}; };
@ -143,7 +143,7 @@ impl RepoDetails {
// load config file // load config file
let config_filename = &self.gitdir.join("config"); let config_filename = &self.gitdir.join("config");
let file = fs.file(config_filename); let file = fs.file(config_filename);
let config_file = file.reader()?.to_string(); let config_file = file.reader()?;
let mut config_lines = config_file let mut config_lines = config_file
.lines() .lines()
.map(ToOwned::to_owned) .map(ToOwned::to_owned)
@ -152,7 +152,7 @@ impl RepoDetails {
let url_line = format!(r#" url = "{url}""#); let url_line = format!(r#" url = "{url}""#);
if config_lines if config_lines
.iter() .iter()
.any(|line| *line == r#"[remote "origin"]"#) .any(|line| line == r#"[remote "origin"]"#)
{ {
tracing::debug!("has an 'origin' remote"); tracing::debug!("has an 'origin' remote");
config_lines config_lines
@ -161,12 +161,12 @@ impl RepoDetails {
.for_each(|line| line.clone_from(&url_line)); .for_each(|line| line.clone_from(&url_line));
} else { } else {
tracing::debug!("has no 'origin' remote"); 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); config_lines.push(url_line);
} }
tracing::debug!(?config_lines, "updated file"); tracing::debug!(?config_lines, "updated file");
// write config file back out // write config file back out
file.write(config_lines.join("\n").as_str())?; file.write(config_lines.join("\n"))?;
Ok(()) Ok(())
} }
} }

View file

@ -1,11 +1,14 @@
// //
use crate::git::{ use crate::{
self, git::{
repository::{ self,
open::{oreal::RealOpenRepository, OpenRepositoryLike}, repository::{
Direction, Result, open::{oreal::RealOpenRepository, OpenRepositoryLike},
Direction, Result,
},
RepoDetails,
}, },
RepoDetails, s,
}; };
use secrecy::ExposeSecret as _; use secrecy::ExposeSecret as _;
@ -51,7 +54,7 @@ impl RepositoryFactory for RealRepositoryFactory {
fn open(&self, repo_details: &RepoDetails) -> Result<Box<dyn OpenRepositoryLike>> { fn open(&self, repo_details: &RepoDetails) -> Result<Box<dyn OpenRepositoryLike>> {
let repo = repo_details let repo = repo_details
.open() .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); let found = repo.find_default_remote(Direction::Fetch);
repo_details.assert_remote_url(found)?; repo_details.assert_remote_url(found)?;

View file

@ -46,6 +46,8 @@ pub fn open(
repository_factory: &dyn factory::RepositoryFactory, repository_factory: &dyn factory::RepositoryFactory,
repo_details: &RepoDetails, repo_details: &RepoDetails,
) -> Result<Box<dyn OpenRepositoryLike>> { ) -> Result<Box<dyn OpenRepositoryLike>> {
use crate::s;
let open_repository = if repo_details.gitdir.exists() { let open_repository = if repo_details.gitdir.exists() {
info!("Local copy found - opening..."); info!("Local copy found - opening...");
let repo = repository_factory.open(repo_details)?; let repo = repository_factory.open(repo_details)?;
@ -57,7 +59,7 @@ pub fn open(
}; };
info!("Validating..."); info!("Validating...");
validate_default_remotes(&*open_repository, repo_details) 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) Ok(open_repository)
} }
@ -140,21 +142,24 @@ pub enum Error {
} }
mod gix_errors { 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; use super::Error;
impl From<gix::clone::Error> for Error { impl From<gix::clone::Error> for Error {
fn from(value: gix::clone::Error) -> Self { fn from(value: gix::clone::Error) -> Self {
Self::Clone(value.to_string()) Self::Clone(s!(value))
} }
} }
impl From<gix::open::Error> for Error { impl From<gix::open::Error> for Error {
fn from(value: gix::open::Error) -> Self { fn from(value: gix::open::Error) -> Self {
Self::Open(value.to_string()) Self::Open(s!(value))
} }
} }
impl From<gix::clone::fetch::Error> for Error { impl From<gix::clone::fetch::Error> for Error {
fn from(value: gix::clone::fetch::Error) -> Self { fn from(value: gix::clone::fetch::Error) -> Self {
Self::Fetch(value.to_string()) Self::Fetch(s!(value))
} }
} }
} }

View file

@ -1,7 +1,7 @@
// //
use crate::{ use crate::{
git::{self, repository::OpenRepositoryLike}, git::{self, repository::OpenRepositoryLike},
BranchName, ForgeDetails, Hostname, RemoteUrl, RepoPath, s, BranchName, ForgeDetails, Hostname, RemoteUrl, RepoPath,
}; };
use derive_more::Constructor; use derive_more::Constructor;
@ -31,7 +31,7 @@ impl super::OpenRepositoryLike for RealOpenRepository {
Ok(refs.remote_branches().map(|rb| { Ok(refs.remote_branches().map(|rb| {
rb.filter_map(Result::ok) rb.filter_map(Result::ok)
.map(|r| r.name().to_owned()) .map(|r| r.name().to_owned())
.map(|n| n.to_string()) .map(|n| s!(n))
.filter_map(|p| { .filter_map(|p| {
p.strip_prefix("refs/remotes/origin/") p.strip_prefix("refs/remotes/origin/")
.map(ToOwned::to_owned) .map(ToOwned::to_owned)
@ -157,39 +157,38 @@ impl super::OpenRepositoryLike for RealOpenRepository {
let thread_local = repo.to_thread_local(); let thread_local = repo.to_thread_local();
let branch_head = thread_local let branch_head = thread_local
.rev_parse_single(branch) .rev_parse_single(branch)
.map_err(|e| e.to_string()) .map_err(|e| s!(e))
.map_err(as_gix_error(branch_name.clone()))?; .map_err(as_gix_error(branch_name.clone()))?;
let object = branch_head let object = branch_head
.object() .object()
.map_err(|e| e.to_string()) .map_err(|e| s!(e))
.map_err(as_gix_error(branch_name.clone()))?; .map_err(as_gix_error(branch_name.clone()))?;
let commit = object let commit = object
.try_into_commit() .try_into_commit()
.map_err(|e| e.to_string()) .map_err(|e| s!(e))
.map_err(as_gix_error(branch_name.clone()))?; .map_err(as_gix_error(branch_name.clone()))?;
let walk = thread_local let walk = thread_local
.rev_walk([commit.id]) .rev_walk([commit.id])
.all() .all()
.map_err(|e| e.to_string()) .map_err(|e| s!(e))
.map_err(as_gix_error(branch_name.clone()))?; .map_err(as_gix_error(branch_name.clone()))?;
let mut commits = vec![]; let mut commits = vec![];
for item in walk.take(limit) { for item in walk.take(limit) {
let item = item let item = item
.map_err(|e| e.to_string()) .map_err(|e| s!(e))
.map_err(as_gix_error(branch_name.clone()))?; .map_err(as_gix_error(branch_name.clone()))?;
let commit = item let commit = item
.object() .object()
.map_err(|e| e.to_string()) .map_err(|e| s!(e))
.map_err(as_gix_error(branch_name.clone()))?; .map_err(as_gix_error(branch_name.clone()))?;
let id = commit.id().to_string(); let id = commit.id();
let message = commit let message = commit
.message_raw() .message_raw()
.map_err(|e| e.to_string()) .map_err(|e| s!(e))
.map_err(as_gix_error(branch_name.clone()))? .map_err(as_gix_error(branch_name.clone()))?;
.to_string();
let commit = git::Commit::new( let commit = git::Commit::new(
git::commit::Sha::new(id), git::commit::Sha::new(s!(id)),
git::commit::Message::new(message), git::commit::Message::new(s!(message)),
); );
if find_commits.contains(&commit) { if find_commits.contains(&commit) {
commits.push(commit); commits.push(commit);
@ -215,7 +214,7 @@ impl super::OpenRepositoryLike for RealOpenRepository {
let commit = obj.into_commit(); let commit = obj.into_commit();
let tree = commit.tree()?; let tree = commit.tree()?;
let ent = 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)?; .ok_or(git::file::Error::FileNotFound)?;
let fobj = ent.object()?; let fobj = ent.object()?;
let blob = fobj.into_blob().take_data(); 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 { impl From<&RemoteUrl> for git::GitRemote {
fn from(url: &RemoteUrl) -> Self { fn from(url: &RemoteUrl) -> Self {
let host = url.host.clone().unwrap_or_default(); 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_prefix('/').map_or(path.as_str(), |path| path);
let path = path.strip_suffix(".git").map_or(path, |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)))
} }
} }

View file

@ -4,7 +4,7 @@ use crate::{
self, self,
repository::open::{OpenRepositoryLike, RealOpenRepository}, repository::open::{OpenRepositoryLike, RealOpenRepository},
}, },
BranchName, ForgeDetails, GitDir, RemoteUrl, RepoBranches, s, BranchName, ForgeDetails, GitDir, RemoteUrl, RepoBranches,
}; };
use derive_more::Constructor; use derive_more::Constructor;
@ -174,10 +174,7 @@ impl TestOpenRepository {
let config_file = fs.base().join(gitdir.to_path_buf()).join(".git/config"); let config_file = fs.base().join(gitdir.to_path_buf()).join(".git/config");
let file = fs.file(&config_file); let file = fs.file(&config_file);
#[allow(clippy::expect_used)] #[allow(clippy::expect_used)]
let contents = file let contents = s!(file.reader().expect("read original .git/config"));
.reader()
.expect("read original .git/config")
.to_string();
let updated_contents = format!( let updated_contents = format!(
r#"{contents} r#"{contents}
[remote "origin"] [remote "origin"]

View file

@ -1,3 +1,5 @@
use crate::s;
// //
use super::*; use super::*;
@ -23,7 +25,7 @@ fn open_where_storage_external_auth_matches() -> TestResult {
tracing::debug!(?result, "open"); tracing::debug!(?result, "open");
assert!(result.is_ok()); assert!(result.is_ok());
// verify origin in .git/config matches url // 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::<Vec<_>>(), "auth"); tracing::debug!(config=?config.lines().collect::<Vec<_>>(), "auth");
assert!(config.lines().any(|line| line.contains(url))); assert!(config.lines().any(|line| line.contains(url)));
Ok(()) Ok(())
@ -60,7 +62,7 @@ fn open_where_storage_external_auth_differs_error() -> TestResult {
)); ));
// verify origin in .git/config is unchanged // 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::<Vec<_>>(), "auth"); tracing::debug!(config=?config.lines().collect::<Vec<_>>(), "auth");
assert!(config.lines().any(|line| line.contains(original_url))); // the original urk assert!(config.lines().any(|line| line.contains(original_url))); // the original urk
Ok(()) Ok(())
@ -86,7 +88,7 @@ fn open_where_storage_internal_auth_matches() -> TestResult {
tracing::debug!(?result, "open"); tracing::debug!(?result, "open");
assert!(result.is_ok()); assert!(result.is_ok());
// verify origin in .git/config matches url // 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::<Vec<_>>(), "auth"); tracing::debug!(config=?config.lines().collect::<Vec<_>>(), "auth");
assert!( assert!(
config.lines().any(|line| line.contains(url)), 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()); assert!(result.is_ok());
// verify origin in .git/config is unchanged // 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::<Vec<_>>(), "auth"); tracing::debug!(config=?config.lines().collect::<Vec<_>>(), "auth");
assert!( assert!(
config config

View file

@ -2,7 +2,7 @@
use crate::{ use crate::{
git::{self, Generation, GitRef, GitRemote, RepoDetails}, git::{self, Generation, GitRef, GitRemote, RepoDetails},
git_dir::StoragePathType, 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, RepoAlias, RepoBranches, RepoConfig, RepoConfigSource, RepoPath, ServerRepoConfig,
}; };
@ -17,6 +17,7 @@ use std::{
type TestResult = Result<(), Box<dyn std::error::Error>>; type TestResult = Result<(), Box<dyn std::error::Error>>;
mod commit { mod commit {
use super::*; use super::*;
#[test] #[test]
@ -41,24 +42,25 @@ mod commit {
let commit = git::Commit::from(push); let commit = git::Commit::from(push);
let expected = git::Commit::new( let expected = git::Commit::new(
git::commit::Sha::new(sha.to_string()), git::commit::Sha::new(sha),
git::commit::Message::new(message.to_string()), git::commit::Message::new(message),
); );
assert_eq!(commit, expected); assert_eq!(commit, expected);
} }
} }
mod generation { mod generation {
use super::*; use super::*;
#[test] #[test]
fn should_increment() { fn should_increment() {
let mut g = Generation::default(); let mut g = Generation::default();
assert_eq!(g.to_string(), "0"); assert_eq!(s!(g), "0");
g.inc(); g.inc();
assert_eq!(g.to_string(), "1"); assert_eq!(s!(g), "1");
} }
} }
mod gitref { mod gitref {
@ -67,12 +69,12 @@ mod gitref {
#[test] #[test]
fn should_convert_from_commit() { fn should_convert_from_commit() {
let commit = git::Commit::new( let commit = git::Commit::new(
git::commit::Sha::new("sha".to_string()), git::commit::Sha::new("sha"),
git::commit::Message::new("message".to_string()), git::commit::Message::new("message"),
); );
let gitref = GitRef::from(commit); let gitref = GitRef::from(commit);
assert_eq!(gitref.to_string(), "sha"); assert_eq!(s!(gitref), "sha");
} }
} }
mod gitremote { mod gitremote {
@ -81,16 +83,16 @@ mod gitremote {
#[test] #[test]
fn should_return_hostname() { fn should_return_hostname() {
let host = Hostname::new("localhost".to_string()); let host = Hostname::new("localhost");
let repo_path = RepoPath::new("kemitix/git-next".to_string()); let repo_path = RepoPath::new(s!("kemitix/git-next"));
let gr = GitRemote::new(host.clone(), repo_path); let gr = GitRemote::new(host.clone(), repo_path);
assert_eq!(gr.host(), &host); assert_eq!(gr.host(), &host);
} }
#[test] #[test]
fn should_return_repo_path() { fn should_return_repo_path() {
let host = Hostname::new("localhost".to_string()); let host = Hostname::new("localhost");
let repo_path = RepoPath::new("kemitix/git-next".to_string()); let repo_path = RepoPath::new(s!("kemitix/git-next"));
let gr = GitRemote::new(host, repo_path.clone()); let gr = GitRemote::new(host, repo_path.clone());
assert_eq!(gr.repo_path(), &repo_path); assert_eq!(gr.repo_path(), &repo_path);
@ -101,7 +103,7 @@ mod push {
#[test] #[test]
fn force_no_should_display() { 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] #[test]
@ -109,7 +111,7 @@ mod push {
let sha = given::a_name(); let sha = given::a_name();
let commit = given::a_commit_with_sha(&git::commit::Sha::new(sha.clone())); let commit = given::a_commit_with_sha(&git::commit::Sha::new(sha.clone()));
assert_eq!( assert_eq!(
git::push::Force::From(GitRef::from(commit)).to_string(), s!(git::push::Force::From(GitRef::from(commit))),
format!("force-if-from:{sha}") format!("force-if-from:{sha}")
); );
} }
@ -158,20 +160,13 @@ mod repo_details {
let rd = RepoDetails::new( let rd = RepoDetails::new(
Generation::default(), Generation::default(),
&RepoAlias::new("foo"), &RepoAlias::new("foo"),
&ServerRepoConfig::new( &ServerRepoConfig::new(s!("repo"), s!("branch"), None, None, None, None),
"repo".to_string(), &ForgeAlias::new("default"),
"branch".to_string(),
None,
None,
None,
None,
),
&ForgeAlias::new("default".to_string()),
&ForgeConfig::new( &ForgeConfig::new(
ForgeType::MockForge, ForgeType::MockForge,
"host".to_string(), s!("host"),
"user".to_string(), s!("user"),
"token".to_string(), s!("token"),
given::maybe_a_number(), // max dev commits given::maybe_a_number(), // max dev commits
BTreeMap::new(), BTreeMap::new(),
), ),
@ -303,7 +298,7 @@ pub mod given {
pub fn a_webhook_push(sha: &git::commit::Sha, message: &git::commit::Message) -> webhook::Push { pub fn a_webhook_push(sha: &git::commit::Sha, message: &git::commit::Message) -> webhook::Push {
let branch = a_branch_name(); 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 { pub fn a_filesystem() -> kxio::fs::TempFileSystem {
@ -338,7 +333,7 @@ pub mod given {
repo.persist(); repo.persist();
// load config file // load config file
let file = fs.file(&path.join("config")); 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 // add use are origin url
let mut config_lines = config_file.lines().collect::<Vec<_>>(); let mut config_lines = config_file.lines().collect::<Vec<_>>();
config_lines.push(r#"[remote "origin"]"#); config_lines.push(r#"[remote "origin"]"#);
@ -417,12 +412,12 @@ pub mod then {
.join(gitdir.to_path_buf()) .join(gitdir.to_path_buf())
.join(".git") .join(".git")
.join("refs"); .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 origin_heads = gitrefs.join("remotes").join("origin");
let remote_branch = origin_heads.join(branch_name.to_string().as_str()); let remote_branch = origin_heads.join(branch_name.as_str());
let contents = fs.file(&local_branch).reader()?.to_string(); let contents = fs.file(&local_branch).reader()?;
fs.dir(&origin_heads).create_all()?; fs.dir(&origin_heads).create_all()?;
fs.file(&remote_branch).write(&contents)?; fs.file(&remote_branch).write(s!(contents))?;
Ok(()) Ok(())
} }
@ -431,7 +426,7 @@ pub mod then {
&format!("git checkout -b {branch_name}"), &format!("git checkout -b {branch_name}"),
std::process::Command::new("/usr/bin/git") std::process::Command::new("/usr/bin/git")
.current_dir(gitdir.to_path_buf()) .current_dir(gitdir.to_path_buf())
.args(["checkout", "-b", branch_name.to_string().as_str()]) .args(["checkout", "-b", branch_name.as_str()])
.output(), .output(),
)?; )?;
Ok(()) Ok(())
@ -442,7 +437,7 @@ pub mod then {
&format!("git switch {branch_name}"), &format!("git switch {branch_name}"),
std::process::Command::new("/usr/bin/git") std::process::Command::new("/usr/bin/git")
.current_dir(gitdir.to_path_buf()) .current_dir(gitdir.to_path_buf())
.args(["switch", branch_name.to_string().as_str()]) .args(["switch", branch_name.as_str()])
.output(), .output(),
) )
} }
@ -474,7 +469,7 @@ pub mod then {
&format!("git add {file:?}"), &format!("git add {file:?}"),
std::process::Command::new("/usr/bin/git") std::process::Command::new("/usr/bin/git")
.current_dir(gitdir.to_path_buf()) .current_dir(gitdir.to_path_buf())
.args(["add", file.display().to_string().as_str()]) .args(["add", s!(file.display()).as_str()])
.output(), .output(),
) )
} }
@ -484,10 +479,7 @@ pub mod then {
&format!(r#"git commit -m"Added {file:?}""#), &format!(r#"git commit -m"Added {file:?}""#),
std::process::Command::new("/usr/bin/git") std::process::Command::new("/usr/bin/git")
.current_dir(gitdir.to_path_buf()) .current_dir(gitdir.to_path_buf())
.args([ .args(["commit", format!(r#"-m"Added {}"#, file.display()).as_str()])
"commit",
format!(r#"-m"Added {}"#, file.display().to_string().as_str()).as_str(),
])
.output(), .output(),
) )
} }
@ -513,8 +505,8 @@ pub mod then {
.join(".git") .join(".git")
.join("refs") .join("refs")
.join("heads") .join("heads")
.join(branch_name.to_string().as_str()); .join(branch_name.as_str());
let sha = fs.file(&main_ref).reader()?.to_string(); let sha = fs.file(&main_ref).reader()?;
Ok(git::commit::Sha::new(sha.trim().to_string())) Ok(git::commit::Sha::new(s!(sha).trim()))
} }
} }

View file

@ -37,7 +37,7 @@ pub enum UserNotification {
impl UserNotification { impl UserNotification {
#[must_use] #[must_use]
pub fn as_json(&self, timestamp: time::OffsetDateTime) -> serde_json::Value { 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 { match self {
Self::CICheckFailed { Self::CICheckFailed {
forge_alias, forge_alias,

View file

@ -1,7 +1,7 @@
// //
use crate::{ use crate::{
git::{self, repository::open::OpenRepositoryLike, RepoDetails, UserNotification}, git::{self, repository::open::OpenRepositoryLike, RepoDetails, UserNotification},
BranchName, RepoConfig, s, BranchName, RepoConfig,
}; };
use tracing::{debug, instrument}; use tracing::{debug, instrument};
@ -179,11 +179,11 @@ pub enum Error {
} }
impl From<git::fetch::Error> for Error { impl From<git::fetch::Error> for Error {
fn from(value: git::fetch::Error) -> Self { fn from(value: git::fetch::Error) -> Self {
Self::Retryable(value.to_string()) Self::Retryable(s!(value))
} }
} }
impl From<git::commit::log::Error> for Error { impl From<git::commit::log::Error> for Error {
fn from(value: git::commit::log::Error) -> Self { fn from(value: git::commit::log::Error) -> Self {
Self::Retryable(value.to_string()) Self::Retryable(s!(value))
} }
} }

View file

@ -1,7 +1,7 @@
// //
use crate::{ use crate::{
git::{self, repository::open::OpenRepositoryLike}, git::{self, repository::open::OpenRepositoryLike},
RemoteUrl, s, RemoteUrl,
}; };
use tracing::info; use tracing::info;
@ -18,9 +18,9 @@ pub fn validate_default_remotes(
.find_default_remote(git::repository::Direction::Fetch) .find_default_remote(git::repository::Direction::Fetch)
.ok_or(Error::NoDefaultFetchRemote)?; .ok_or(Error::NoDefaultFetchRemote)?;
let Some(remote_url) = repo_details.remote_url() else { let Some(remote_url) = repo_details.remote_url() else {
return Err(git::validation::remotes::Error::UnableToOpenRepo( return Err(git::validation::remotes::Error::UnableToOpenRepo(s!(
"Unable to build forge url".to_string(), "Unable to build forge url"
)); )));
}; };
info!(config = %remote_url, push = %push_remote, fetch = %fetch_remote, "Check remotes match"); info!(config = %remote_url, push = %push_remote, fetch = %fetch_remote, "Check remotes match");
if !remote_url.matches(&push_remote) { if !remote_url.matches(&push_remote) {

View file

@ -10,7 +10,7 @@ use crate::{
tests::{given, then}, tests::{given, then},
validation::positions::validate, validation::positions::validate,
}, },
GitDir, StoragePathType, s, GitDir, StoragePathType,
}; };
use assert2::let_assert; use assert2::let_assert;
@ -102,7 +102,7 @@ mod positions {
if branch_name == &main_branch { if branch_name == &main_branch {
Err(git::commit::log::Error::Gix { Err(git::commit::log::Error::Gix {
branch: branch_name.clone(), branch: branch_name.clone(),
error: "foo".to_string(), error: s!("foo"),
}) })
} else { } else {
Ok(vec![]) Ok(vec![])
@ -141,7 +141,7 @@ mod positions {
if branch_name == &next_branch { if branch_name == &next_branch {
Err(git::commit::log::Error::Gix { Err(git::commit::log::Error::Gix {
branch: branch_name.clone(), branch: branch_name.clone(),
error: "foo".to_string(), error: s!("foo"),
}) })
} else { } else {
Ok(vec![given::a_commit()]) Ok(vec![given::a_commit()])
@ -180,7 +180,7 @@ mod positions {
if branch_name == &dev_branch { if branch_name == &dev_branch {
Err(git::commit::log::Error::Gix { Err(git::commit::log::Error::Gix {
branch: branch_name.clone(), branch: branch_name.clone(),
error: "foo".to_string(), error: s!("foo"),
}) })
} else { } else {
Ok(vec![given::a_commit()]) Ok(vec![given::a_commit()])

View file

@ -1,2 +1,15 @@
mod message; mod message;
mod newtype; 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");
}
}

View file

@ -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()
};
}