Compare commits

...

7 commits

Author SHA1 Message Date
7d953c1947 WIP: mock repository
All checks were successful
ci/woodpecker/push/push-next Pipeline was successful
ci/woodpecker/push/cron-docker-builder Pipeline was successful
ci/woodpecker/push/tag-created Pipeline was successful
2024-05-20 07:46:23 +01:00
c6c8dcedc5 feat(server): display expected auth in logs in invalid request
All checks were successful
Rust / build (push) Successful in 1m43s
ci/woodpecker/push/push-next Pipeline was successful
ci/woodpecker/push/cron-docker-builder Pipeline was successful
ci/woodpecker/push/tag-created Pipeline was successful
2024-05-20 07:46:23 +01:00
4977619c70 fix(server): don't use gix in server
All checks were successful
Rust / build (push) Successful in 1m35s
ci/woodpecker/push/push-next Pipeline was successful
ci/woodpecker/push/cron-docker-builder Pipeline was successful
ci/woodpecker/push/tag-created Pipeline was successful
2024-05-20 07:46:23 +01:00
c3c4c41c73 refactor(git): only expose OpenRepository from repository::open
All checks were successful
Rust / build (push) Successful in 1m29s
ci/woodpecker/push/cron-docker-builder Pipeline was successful
ci/woodpecker/push/push-next Pipeline was successful
ci/woodpecker/push/tag-created Pipeline was successful
2024-05-20 07:46:21 +01:00
70100f6dc5 refactor(git): reporitory errors don't leak implementation
All checks were successful
Rust / build (push) Successful in 1m40s
ci/woodpecker/push/push-next Pipeline was successful
ci/woodpecker/push/cron-docker-builder Pipeline was successful
ci/woodpecker/push/tag-created Pipeline was successful
2024-05-20 07:43:03 +01:00
155497c97f refactor(git): split mock, real and open into their files
All checks were successful
Rust / build (push) Successful in 1m46s
ci/woodpecker/push/cron-docker-builder Pipeline was successful
ci/woodpecker/push/push-next Pipeline was successful
ci/woodpecker/push/tag-created Pipeline was successful
2024-05-20 07:42:52 +01:00
7b1575eb09 build(justfile): validate format locally
All checks were successful
Rust / build (push) Successful in 1m39s
ci/woodpecker/push/push-next Pipeline was successful
ci/woodpecker/push/cron-docker-builder Pipeline was successful
ci/woodpecker/push/tag-created Pipeline was successful
2024-05-20 07:42:33 +01:00
29 changed files with 472 additions and 285 deletions

View file

@ -62,6 +62,7 @@ derive_more = { version = "1.0.0-beta.6", features = [
"deref", "deref",
"from", "from",
] } ] }
derive-with = "0.5"
# file watcher # file watcher
inotify = "0.10" inotify = "0.10"

View file

@ -40,9 +40,10 @@ secrecy = { workspace = true }
# bytes = { workspace = true } # bytes = { workspace = true }
# ulid = { workspace = true } # ulid = { workspace = true }
# warp = { workspace = true } # warp = { workspace = true }
#
# # error handling # boilerplate
derive_more = { workspace = true } derive_more = { workspace = true }
derive-with = { workspace = true }
# #
# # file watcher # # file watcher
# inotify = { workspace = true } # inotify = { workspace = true }

View file

@ -9,3 +9,8 @@ impl secrecy::ExposeSecret<String> for ApiToken {
self.0.expose_secret() self.0.expose_secret()
} }
} }
impl Default for ApiToken {
fn default() -> Self {
Self("".to_string().into())
}
}

View file

@ -1,5 +1,5 @@
/// The name of a Branch /// The name of a Branch
#[derive(Clone, Debug, Hash, PartialEq, Eq, derive_more::Display)] #[derive(Clone, Default, Debug, Hash, PartialEq, Eq, derive_more::Display)]
pub struct BranchName(String); pub struct BranchName(String);
impl BranchName { impl BranchName {
pub fn new(str: impl Into<String>) -> Self { pub fn new(str: impl Into<String>) -> Self {

View file

@ -1,7 +1,7 @@
use crate::{ApiToken, ForgeConfig, ForgeName, ForgeType, Hostname, User}; use crate::{ApiToken, ForgeConfig, ForgeName, ForgeType, Hostname, User};
/// The derived information about a Forge, used to create interactions with it /// The derived information about a Forge, used to create interactions with it
#[derive(Clone, Debug, derive_more::Constructor)] #[derive(Clone, Default, Debug, derive_more::Constructor, derive_with::With)]
pub struct ForgeDetails { pub struct ForgeDetails {
forge_name: ForgeName, forge_name: ForgeName,
forge_type: ForgeType, forge_type: ForgeType,
@ -27,11 +27,6 @@ impl ForgeDetails {
pub const fn token(&self) -> &ApiToken { pub const fn token(&self) -> &ApiToken {
&self.token &self.token
} }
pub fn with_hostname(self, hostname: Hostname) -> Self {
let mut me = self;
me.hostname = hostname;
me
}
} }
impl From<(&ForgeName, &ForgeConfig)> for ForgeDetails { impl From<(&ForgeName, &ForgeConfig)> for ForgeDetails {
fn from(forge: (&ForgeName, &ForgeConfig)) -> Self { fn from(forge: (&ForgeName, &ForgeConfig)) -> Self {

View file

@ -1,7 +1,7 @@
use std::path::PathBuf; use std::path::PathBuf;
/// The name of a Forge to connect to /// The name of a Forge to connect to
#[derive(Clone, Debug, PartialEq, Eq, derive_more::Constructor, derive_more::Display)] #[derive(Clone, Default, Debug, PartialEq, Eq, derive_more::Constructor, derive_more::Display)]
pub struct ForgeName(String); pub struct ForgeName(String);
impl From<&ForgeName> for PathBuf { impl From<&ForgeName> for PathBuf {
fn from(value: &ForgeName) -> Self { fn from(value: &ForgeName) -> Self {

View file

@ -1,5 +1,5 @@
/// Identifier for the type of Forge /// Identifier for the type of Forge
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize)] #[derive(Clone, Default, Copy, Debug, PartialEq, Eq, serde::Deserialize)]
pub enum ForgeType { pub enum ForgeType {
#[cfg(feature = "forgejo")] #[cfg(feature = "forgejo")]
ForgeJo, ForgeJo,
@ -7,6 +7,7 @@ pub enum ForgeType {
// GitHub, // GitHub,
// GitLab, // GitLab,
// BitBucket, // BitBucket,
#[default]
MockForge, MockForge,
} }
impl std::fmt::Display for ForgeType { impl std::fmt::Display for ForgeType {

View file

@ -1,7 +1,15 @@
use std::path::PathBuf; use std::path::PathBuf;
#[derive( #[derive(
Debug, Clone, PartialEq, Eq, serde::Deserialize, derive_more::Deref, derive_more::From, Clone,
Default,
Debug,
Hash,
PartialEq,
Eq,
serde::Deserialize,
derive_more::Deref,
derive_more::From,
)] )]
pub struct GitDir(PathBuf); pub struct GitDir(PathBuf);
impl GitDir { impl GitDir {

View file

@ -1,5 +1,5 @@
/// The hostname of a forge /// The hostname of a forge
#[derive(Clone, Debug, PartialEq, Eq, derive_more::Display)] #[derive(Clone, Default, Debug, PartialEq, Eq, derive_more::Display)]
pub struct Hostname(String); pub struct Hostname(String);
impl Hostname { impl Hostname {
pub fn new(str: impl Into<String>) -> Self { pub fn new(str: impl Into<String>) -> Self {

View file

@ -1,6 +1,6 @@
/// The alias of a repo /// The alias of a repo
/// This is the alias for the repo within `git-next-server.toml` /// This is the alias for the repo within `git-next-server.toml`
#[derive(Clone, Debug, PartialEq, Eq, Hash, derive_more::Display)] #[derive(Clone, Default, Debug, PartialEq, Eq, Hash, derive_more::Display)]
pub struct RepoAlias(String); pub struct RepoAlias(String);
impl RepoAlias { impl RepoAlias {
pub fn new(str: impl Into<String>) -> Self { pub fn new(str: impl Into<String>) -> Self {

View file

@ -1,5 +1,5 @@
/// The path for the repo within the forge. /// The path for the repo within the forge.
/// Typically this is composed of the user or organisation and the name of the repo /// Typically this is composed of the user or organisation and the name of the repo
/// e.g. `{user}/{repo}` /// e.g. `{user}/{repo}`
#[derive(Clone, Debug, PartialEq, Eq, derive_more::Constructor, derive_more::Display)] #[derive(Clone, Default, Debug, PartialEq, Eq, derive_more::Constructor, derive_more::Display)]
pub struct RepoPath(String); pub struct RepoPath(String);

View file

@ -1,3 +1,3 @@
/// The user within the forge to connect as /// The user within the forge to connect as
#[derive(Clone, Debug, PartialEq, Eq, derive_more::Constructor, derive_more::Display)] #[derive(Clone, Default, Debug, PartialEq, Eq, derive_more::Constructor, derive_more::Display)]
pub struct User(String); pub struct User(String);

View file

@ -45,6 +45,7 @@ secrecy = { workspace = true }
# error handling # error handling
derive_more = { workspace = true } derive_more = { workspace = true }
derive-with = { workspace = true }
# # file watcher # # file watcher
# inotify = { workspace = true } # inotify = { workspace = true }
@ -54,9 +55,9 @@ derive_more = { workspace = true }
# actix-rt = { workspace = true } # actix-rt = { workspace = true }
# tokio = { workspace = true } # tokio = { workspace = true }
# #
# [dev-dependencies] [dev-dependencies]
# # Testing # Testing
# assert2 = { workspace = true } assert2 = { workspace = true }
[lints.clippy] [lints.clippy]
nursery = { level = "warn", priority = -1 } nursery = { level = "warn", priority = -1 }

View file

@ -17,6 +17,6 @@ pub use generation::Generation;
pub use git_ref::GitRef; pub use git_ref::GitRef;
pub use git_remote::GitRemote; pub use git_remote::GitRemote;
pub use repo_details::RepoDetails; pub use repo_details::RepoDetails;
pub use repository::open::OpenRepository; pub use repository::OpenRepository;
pub use repository::Repository; pub use repository::Repository;
pub use validate::validate; pub use validate::validate;

View file

@ -6,7 +6,7 @@ use git_next_config::{
use super::{Generation, GitRemote}; use super::{Generation, GitRemote};
/// The derived information about a repo, used to interact with it /// The derived information about a repo, used to interact with it
#[derive(Clone, Debug, derive_more::Display)] #[derive(Clone, Default, Debug, derive_more::Display, derive_with::With)]
#[display("gen-{}:{}:{}/{}:{}@{}/{}@{}", generation, forge.forge_type(), #[display("gen-{}:{}:{}/{}:{}@{}/{}@{}", generation, forge.forge_type(),
forge.forge_name(), repo_alias, forge.user(), forge.hostname(), repo_path, forge.forge_name(), repo_alias, forge.user(), forge.hostname(), repo_path,
branch)] branch)]

View file

@ -1,249 +0,0 @@
//
#![cfg(not(tarpaulin_include))]
use std::{
ops::Deref as _,
sync::{atomic::AtomicBool, Arc, Mutex},
};
use git_next_config::{BranchName, GitDir, Hostname, RepoPath};
use tracing::{info, warn};
use crate::{fetch, push, GitRef, GitRemote};
use super::RepoDetails;
#[derive(Clone, Copy, Debug)]
pub enum Repository {
Real,
Mock,
}
pub const fn new() -> Repository {
Repository::Real
}
pub const fn mock() -> Repository {
Repository::Mock
}
mod mock {
use super::*;
pub struct MockRepository;
impl RepositoryLike for MockRepository {
fn open(&self, _gitdir: &GitDir) -> Result<open::OpenRepository, Error> {
Ok(open::OpenRepository::Mock)
}
fn git_clone(&self, _repo_details: &RepoDetails) -> Result<open::OpenRepository, Error> {
Ok(open::OpenRepository::Mock)
}
}
}
pub trait RepositoryLike {
fn open(&self, gitdir: &GitDir) -> Result<open::OpenRepository, Error>;
fn git_clone(&self, repo_details: &RepoDetails) -> Result<open::OpenRepository, Error>;
}
impl std::ops::Deref for Repository {
type Target = dyn RepositoryLike;
fn deref(&self) -> &Self::Target {
match self {
Self::Real => &real::RealRepository,
Self::Mock => &mock::MockRepository,
}
}
}
mod real {
use super::*;
pub struct RealRepository;
impl RepositoryLike for RealRepository {
fn open(&self, gitdir: &GitDir) -> Result<open::OpenRepository, Error> {
Ok(open::OpenRepository::Real(open::RealOpenRepository::new(
Arc::new(Mutex::new(
gix::ThreadSafeRepository::open(gitdir.to_path_buf())?.to_thread_local(),
)),
)))
}
fn git_clone(&self, repo_details: &RepoDetails) -> Result<open::OpenRepository, Error> {
use secrecy::ExposeSecret;
let origin = repo_details.origin();
let (repository, _outcome) = gix::prepare_clone_bare(
origin.expose_secret().as_str(),
repo_details.gitdir.deref(),
)?
.fetch_only(gix::progress::Discard, &AtomicBool::new(false))?;
Ok(open::OpenRepository::Real(open::RealOpenRepository::new(
Arc::new(Mutex::new(repository)),
)))
}
}
}
pub mod open {
use super::*;
#[derive(Clone, Debug)]
pub enum OpenRepository {
Real(RealOpenRepository),
Mock, // TODO: (#38) contain a mock model of a repo
}
pub trait OpenRepositoryLike {
fn find_default_remote(&self, direction: Direction) -> Option<GitRemote>;
fn fetch(&self) -> Result<(), fetch::Error>;
fn push(
&self,
repo_details: &RepoDetails,
branch_name: BranchName,
to_commit: GitRef,
force: push::Force,
) -> Result<(), push::Error>;
}
impl std::ops::Deref for OpenRepository {
type Target = dyn OpenRepositoryLike;
fn deref(&self) -> &Self::Target {
match self {
Self::Real(real) => real,
Self::Mock => todo!(),
}
}
}
#[derive(Clone, Debug, derive_more::Constructor)]
pub struct RealOpenRepository(Arc<Mutex<gix::Repository>>);
impl OpenRepositoryLike for RealOpenRepository {
fn find_default_remote(&self, direction: Direction) -> Option<GitRemote> {
let Ok(repository) = self.0.lock() else {
return None;
};
let Some(Ok(remote)) = repository.find_default_remote(direction.into()) else {
return None;
};
let url = remote.url(direction.into())?;
let host = url.host()?;
let path = url.path.to_string();
let path = path.strip_prefix('/').map_or(path.as_str(), |path| path);
let path = path.strip_suffix(".git").map_or(path, |path| path);
Some(GitRemote::new(
Hostname::new(host),
RepoPath::new(path.to_string()),
))
}
fn fetch(&self) -> Result<(), fetch::Error> {
let Ok(repository) = self.0.lock() else {
return Err(fetch::Error::Lock);
};
let Some(Ok(remote)) = repository.find_default_remote(Direction::Fetch.into()) else {
return Err(fetch::Error::NoFetchRemoteFound);
};
remote
.connect(gix::remote::Direction::Fetch)
.map_err(|e| fetch::Error::Connect(e.to_string()))?
.prepare_fetch(gix::progress::Discard, Default::default())
.map_err(|e| fetch::Error::Fetch(e.to_string()))?
.receive(gix::progress::Discard, &Default::default())
.map_err(|e| fetch::Error::Fetch(e.to_string()))?;
Ok(())
}
// TODO: (#72) reimplement using `gix`
fn push(
&self,
repo_details: &RepoDetails,
branch_name: BranchName,
to_commit: GitRef,
force: push::Force,
) -> Result<(), push::Error> {
let origin = repo_details.origin();
let force = match force {
push::Force::No => "".to_string(),
push::Force::From(old_ref) => format!("--force-with-lease={branch_name}:{old_ref}"),
};
// INFO: never log the command as it contains the API token within the 'origin'
use secrecy::ExposeSecret;
let command: secrecy::Secret<String> = format!(
"/usr/bin/git push {} {to_commit}:{branch_name} {force}",
origin.expose_secret()
)
.into();
let git_dir = self
.0
.lock()
.map_err(|_| push::Error::Lock)
.map(|r| r.git_dir().to_path_buf())?;
let ctx = gix::diff::command::Context {
git_dir: Some(git_dir.clone()),
..Default::default()
};
match gix::command::prepare(command.expose_secret())
.with_context(ctx)
.with_shell_allow_argument_splitting()
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
{
Ok(mut child) => match child.wait() {
Ok(_) => {
info!("Branch updated");
Ok(())
}
Err(err) => {
warn!(?err, ?git_dir, "Failed (wait)");
Err(push::Error::Push)
}
},
Err(err) => {
warn!(?err, ?git_dir, "Failed (spawn)");
Err(push::Error::Push)
}
}
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Direction {
/// Push local changes to the remote.
Push,
/// Fetch changes from the remote to the local repository.
Fetch,
}
impl From<Direction> for gix::remote::Direction {
fn from(value: Direction) -> Self {
match value {
Direction::Push => Self::Push,
Direction::Fetch => Self::Fetch,
}
}
}
#[derive(Debug, derive_more::Display)]
pub enum Error {
InvalidGitDir(git_next_config::GitDir),
Io(std::io::Error),
Wait(std::io::Error),
Spawn(std::io::Error),
Validation(String),
GixClone(Box<gix::clone::Error>),
GixOpen(Box<gix::open::Error>),
GixFetch(Box<gix::clone::fetch::Error>),
}
impl std::error::Error for Error {}
impl From<gix::clone::Error> for Error {
fn from(value: gix::clone::Error) -> Self {
Self::GixClone(Box::new(value))
}
}
impl From<gix::open::Error> for Error {
fn from(value: gix::open::Error) -> Self {
Self::GixOpen(Box::new(value))
}
}
impl From<gix::clone::fetch::Error> for Error {
fn from(value: gix::clone::fetch::Error) -> Self {
Self::GixFetch(Box::new(value))
}
}

View file

@ -0,0 +1,114 @@
use std::{
collections::HashMap,
sync::{Arc, Mutex},
};
use git_next_config::GitDir;
use crate::{
repository::{
open::{OpenRepository, OpenRepositoryLike},
Direction, RepositoryLike, Result,
},
RepoDetails,
};
use super::Error;
#[derive(Debug, Default, Clone)]
pub struct MockRepository(Arc<Mutex<Reality>>);
impl MockRepository {
pub fn new() -> Self {
Self(Arc::new(Mutex::new(Reality::default())))
}
pub fn can_open_repo(&mut self, gitdir: &GitDir) -> Result<MockOpenRepository> {
self.0
.lock()
.map_err(|_| Error::MockLock)
.map(|mut r| r.can_open_repo(gitdir))
}
fn open_repository(
&self,
gitdir: &GitDir,
) -> std::result::Result<MockOpenRepository, crate::repository::Error> {
self.0.lock().map_err(|_| Error::MockLock).and_then(|r| {
r.open_repository(gitdir)
.ok_or_else(|| Error::Open(format!("mock - could not open: {}", gitdir)))
})
}
fn clone_repository(
&self,
) -> std::result::Result<MockOpenRepository, crate::repository::Error> {
todo!()
}
}
impl RepositoryLike for MockRepository {
fn open(
&self,
gitdir: &GitDir,
) -> std::result::Result<OpenRepository, crate::repository::Error> {
Ok(OpenRepository::Mock(self.open_repository(gitdir)?))
}
fn git_clone(
&self,
_repo_details: &RepoDetails,
) -> std::result::Result<OpenRepository, crate::repository::Error> {
Ok(OpenRepository::Mock(self.clone_repository()?))
}
}
#[derive(Debug, Default)]
pub struct Reality {
openable_repos: HashMap<GitDir, MockOpenRepository>,
}
impl Reality {
pub fn can_open_repo(&mut self, gitdir: &GitDir) -> MockOpenRepository {
let mor = self.openable_repos.get(gitdir);
match mor {
Some(mor) => mor.clone(),
None => {
let mor = MockOpenRepository::default();
self.openable_repos.insert(gitdir.clone(), mor.clone());
mor
}
}
}
pub fn open_repository(&self, gitdir: &GitDir) -> Option<MockOpenRepository> {
self.openable_repos.get(gitdir).cloned()
}
}
#[derive(Clone, Debug, Default)]
pub struct MockOpenRepository {
default_push_remote: Option<String>,
default_fetch_remote: Option<String>,
}
impl MockOpenRepository {
pub fn has_default_remote(&mut self, direction: Direction, url: &str) {
let url = url.to_string();
match direction {
Direction::Push => self.default_push_remote.replace(url),
Direction::Fetch => self.default_fetch_remote.replace(url),
};
}
}
impl OpenRepositoryLike for MockOpenRepository {
fn find_default_remote(&self, direction: Direction) -> Option<crate::GitRemote> {
todo!()
}
fn fetch(&self) -> std::prelude::v1::Result<(), crate::fetch::Error> {
todo!()
}
fn push(
&self,
repo_details: &RepoDetails,
branch_name: git_next_config::BranchName,
to_commit: crate::GitRef,
force: crate::push::Force,
) -> std::prelude::v1::Result<(), crate::push::Error> {
todo!()
}
}

View file

@ -0,0 +1,89 @@
//
#![cfg(not(tarpaulin_include))]
mod mock;
mod open;
mod real;
use git_next_config::GitDir;
pub use open::OpenRepository;
use crate::repository::mock::MockRepository;
use super::RepoDetails;
#[derive(Clone, Debug)]
pub enum Repository {
Real,
Mock(MockRepository),
}
pub const fn new() -> Repository {
Repository::Real
}
pub fn mock() -> (Repository, MockRepository) {
let mock_repository = MockRepository::new();
(Repository::Mock(mock_repository.clone()), mock_repository)
}
pub trait RepositoryLike {
fn open(&self, gitdir: &GitDir) -> Result<OpenRepository>;
fn git_clone(&self, repo_details: &RepoDetails) -> Result<OpenRepository>;
}
impl std::ops::Deref for Repository {
type Target = dyn RepositoryLike;
fn deref(&self) -> &Self::Target {
match self {
Self::Real => &real::RealRepository,
Self::Mock(mock_repository) => mock_repository,
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Direction {
/// Push local changes to the remote.
Push,
/// Fetch changes from the remote to the local repository.
Fetch,
}
impl From<Direction> for gix::remote::Direction {
fn from(value: Direction) -> Self {
match value {
Direction::Push => Self::Push,
Direction::Fetch => Self::Fetch,
}
}
}
pub type Result<T> = core::result::Result<T, Error>;
#[derive(Debug, derive_more::Display)]
pub enum Error {
InvalidGitDir(git_next_config::GitDir),
Io(std::io::Error),
Wait(std::io::Error),
Spawn(std::io::Error),
Validation(String),
Clone(String),
Open(String),
Fetch(String),
MockLock,
}
impl std::error::Error for Error {}
impl From<gix::clone::Error> for Error {
fn from(value: gix::clone::Error) -> Self {
Self::Clone(value.to_string())
}
}
impl From<gix::open::Error> for Error {
fn from(value: gix::open::Error) -> Self {
Self::Open(value.to_string())
}
}
impl From<gix::clone::fetch::Error> for Error {
fn from(value: gix::clone::fetch::Error) -> Self {
Self::Fetch(value.to_string())
}
}

View file

@ -0,0 +1,47 @@
//
pub mod oreal;
use std::sync::{Arc, Mutex};
use git_next_config::BranchName;
use crate::{
fetch, push,
repository::{mock::MockOpenRepository, open::oreal::RealOpenRepository, Direction},
GitRef, GitRemote, RepoDetails,
};
#[derive(Clone, Debug)]
pub enum OpenRepository {
Real(oreal::RealOpenRepository),
Mock(MockOpenRepository), // TODO: (#38) contain a mock model of a repo
}
impl OpenRepository {
pub fn real(gix_repo: gix::Repository) -> Self {
Self::Real(RealOpenRepository::new(Arc::new(Mutex::new(gix_repo))))
}
pub fn mock(mock: MockOpenRepository) -> Self {
Self::Mock(mock)
}
}
pub trait OpenRepositoryLike {
fn find_default_remote(&self, direction: Direction) -> Option<GitRemote>;
fn fetch(&self) -> Result<(), fetch::Error>;
fn push(
&self,
repo_details: &RepoDetails,
branch_name: BranchName,
to_commit: GitRef,
force: push::Force,
) -> Result<(), push::Error>;
}
impl std::ops::Deref for OpenRepository {
type Target = dyn OpenRepositoryLike;
fn deref(&self) -> &Self::Target {
match self {
Self::Real(real) => real,
Self::Mock(mock) => mock,
}
}
}

View file

@ -0,0 +1,102 @@
//
use std::sync::{Arc, Mutex};
use git_next_config::{BranchName, Hostname, RepoPath};
use tracing::{info, warn};
use crate::{fetch, push, repository::Direction, GitRef, GitRemote, RepoDetails};
#[derive(Clone, Debug, derive_more::Constructor)]
pub struct RealOpenRepository(Arc<Mutex<gix::Repository>>);
impl super::OpenRepositoryLike for RealOpenRepository {
fn find_default_remote(&self, direction: Direction) -> Option<GitRemote> {
let Ok(repository) = self.0.lock() else {
return None;
};
let Some(Ok(remote)) = repository.find_default_remote(direction.into()) else {
return None;
};
let url = remote.url(direction.into())?;
let host = url.host()?;
let path = url.path.to_string();
let path = path.strip_prefix('/').map_or(path.as_str(), |path| path);
let path = path.strip_suffix(".git").map_or(path, |path| path);
Some(GitRemote::new(
Hostname::new(host),
RepoPath::new(path.to_string()),
))
}
fn fetch(&self) -> Result<(), fetch::Error> {
let Ok(repository) = self.0.lock() else {
return Err(fetch::Error::Lock);
};
let Some(Ok(remote)) = repository.find_default_remote(Direction::Fetch.into()) else {
return Err(fetch::Error::NoFetchRemoteFound);
};
remote
.connect(gix::remote::Direction::Fetch)
.map_err(|e| fetch::Error::Connect(e.to_string()))?
.prepare_fetch(gix::progress::Discard, Default::default())
.map_err(|e| fetch::Error::Fetch(e.to_string()))?
.receive(gix::progress::Discard, &Default::default())
.map_err(|e| fetch::Error::Fetch(e.to_string()))?;
Ok(())
}
// TODO: (#72) reimplement using `gix`
fn push(
&self,
repo_details: &RepoDetails,
branch_name: BranchName,
to_commit: GitRef,
force: push::Force,
) -> Result<(), push::Error> {
let origin = repo_details.origin();
let force = match force {
push::Force::No => "".to_string(),
push::Force::From(old_ref) => format!("--force-with-lease={branch_name}:{old_ref}"),
};
// INFO: never log the command as it contains the API token within the 'origin'
use secrecy::ExposeSecret;
let command: secrecy::Secret<String> = format!(
"/usr/bin/git push {} {to_commit}:{branch_name} {force}",
origin.expose_secret()
)
.into();
let git_dir = self
.0
.lock()
.map_err(|_| push::Error::Lock)
.map(|r| r.git_dir().to_path_buf())?;
let ctx = gix::diff::command::Context {
git_dir: Some(git_dir.clone()),
..Default::default()
};
match gix::command::prepare(command.expose_secret())
.with_context(ctx)
.with_shell_allow_argument_splitting()
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
{
Ok(mut child) => match child.wait() {
Ok(_) => {
info!("Branch updated");
Ok(())
}
Err(err) => {
warn!(?err, ?git_dir, "Failed (wait)");
Err(push::Error::Push)
}
},
Err(err) => {
warn!(?err, ?git_dir, "Failed (spawn)");
Err(push::Error::Push)
}
}
}
}

View file

@ -0,0 +1,28 @@
use std::sync::atomic::AtomicBool;
use derive_more::Deref as _;
use git_next_config::GitDir;
use crate::{
repository::{open::OpenRepository, Error, RepositoryLike},
RepoDetails,
};
pub struct RealRepository;
impl RepositoryLike for RealRepository {
fn open(&self, gitdir: &GitDir) -> Result<OpenRepository, Error> {
let gix_repo = gix::ThreadSafeRepository::open(gitdir.to_path_buf())?.to_thread_local();
Ok(OpenRepository::real(gix_repo))
}
fn git_clone(&self, repo_details: &RepoDetails) -> Result<OpenRepository, Error> {
use secrecy::ExposeSecret;
let (gix_repo, _outcome) = gix::prepare_clone_bare(
repo_details.origin().expose_secret().as_str(),
repo_details.gitdir.deref(),
)?
.fetch_only(gix::progress::Discard, &AtomicBool::new(false))?;
Ok(OpenRepository::real(gix_repo))
}
}

View file

@ -160,3 +160,33 @@ mod repo_details {
); );
} }
} }
mod repository {
use assert2::let_assert;
use git_next_config::{ForgeDetails, GitDir, Hostname, RepoPath};
use crate::{
repository::{self, Direction},
validate, RepoDetails,
};
#[test]
fn should_ok_a_valid_repo() {
let forge_details =
ForgeDetails::default().with_hostname(Hostname::new("localhost".to_string()));
let repo_details = RepoDetails::default()
.with_forge(forge_details)
.with_repo_path(RepoPath::new("kemitix/test".to_string()));
let gitdir = GitDir::from("foo");
let (repository, mut reality) = repository::mock();
let_assert!(Ok(open_repo_handle) = reality.can_open_repo(&gitdir));
if let Ok(mut open_repo) = open_repo_handle.lock() {
open_repo.has_default_remote(Direction::Push, "https://localhost/kemitix/test");
open_repo.has_default_remote(Direction::Fetch, "https://localhost/kemitix/test");
}
let_assert!(Ok(open_repository) = repository.open(&gitdir));
let_assert!(Ok(_) = validate(&open_repository, &repo_details));
}
}

View file

@ -1,6 +1,6 @@
use tracing::info; use tracing::info;
use crate::repository::{open::OpenRepository, Direction}; use crate::repository::{Direction, OpenRepository};
use super::{GitRemote, RepoDetails}; use super::{GitRemote, RepoDetails};

View file

@ -21,8 +21,6 @@ tracing-subscriber = { workspace = true }
base64 = { workspace = true } base64 = { workspace = true }
# git # git
# gix = { workspace = true }
gix = { workspace = true }
async-trait = { workspace = true } async-trait = { workspace = true }
# fs/network # fs/network

View file

@ -1,7 +1,6 @@
use actix::prelude::*; use actix::prelude::*;
use git_next_git as git; use git_next_git as git;
use gix::trace::warn; use tracing::{info, warn};
use tracing::info;
use crate::{actors::repo::ValidateRepo, gitforge, types::MessageToken}; use crate::{actors::repo::ValidateRepo, gitforge, types::MessageToken};

View file

@ -20,7 +20,7 @@ use crate::{
)] )]
pub struct WebhookId(String); pub struct WebhookId(String);
#[derive(Clone, Debug, PartialEq, Eq, derive_more::Deref)] #[derive(Clone, Debug, PartialEq, Eq, derive_more::Deref, derive_more::Display)]
pub struct WebhookAuth(ulid::Ulid); pub struct WebhookAuth(ulid::Ulid);
impl WebhookAuth { impl WebhookAuth {
pub fn from_str(authorisation: &str) -> Result<Self, DecodeError> { pub fn from_str(authorisation: &str) -> Result<Self, DecodeError> {
@ -33,7 +33,7 @@ impl WebhookAuth {
} }
fn header_value(&self) -> String { fn header_value(&self) -> String {
format!("Basic {}", self.0.to_string()) format!("Basic {}", self)
} }
} }
@ -182,9 +182,20 @@ impl Handler<WebhookMessage> for RepoActor {
#[allow(clippy::cognitive_complexity)] // TODO: (#49) reduce complexity #[allow(clippy::cognitive_complexity)] // TODO: (#49) reduce complexity
#[tracing::instrument(name = "RepoActor::WebhookMessage", skip_all, fields(token = %self.message_token, repo = %self.details))] #[tracing::instrument(name = "RepoActor::WebhookMessage", skip_all, fields(token = %self.message_token, repo = %self.details))]
fn handle(&mut self, msg: WebhookMessage, ctx: &mut Self::Context) -> Self::Result { fn handle(&mut self, msg: WebhookMessage, ctx: &mut Self::Context) -> Self::Result {
if msg.authorisation() != self.webhook_auth { let Some(expected_authorization) = &self.webhook_auth else {
warn!("Invalid authorization"); warn!("Don't know what authorization to expect");
return; // invalid auth return;
};
let Some(received_authorization) = &msg.authorisation() else {
warn!("Missing authorization token");
return;
};
if received_authorization != expected_authorization {
warn!(
"Invalid authorization - expected {}",
expected_authorization
);
return;
} }
let id = msg.id(); let id = msg.id();
let span = tracing::info_span!("handle", %id); let span = tracing::info_span!("handle", %id);

View file

@ -177,7 +177,7 @@ impl Server {
let server_storage = server_storage.clone(); let server_storage = server_storage.clone();
let webhook = webhook.clone(); let webhook = webhook.clone();
let net = self.net.clone(); let net = self.net.clone();
let repo = self.repo; let repo = self.repo.clone();
let generation = self.generation; let generation = self.generation;
move |(repo_alias, server_repo_config)| { move |(repo_alias, server_repo_config)| {
let span = tracing::info_span!("create_actor", alias = %repo_alias, config = %server_repo_config); let span = tracing::info_span!("create_actor", alias = %repo_alias, config = %server_repo_config);
@ -205,8 +205,13 @@ impl Server {
gitdir, gitdir,
); );
info!("Starting Repo Actor"); info!("Starting Repo Actor");
let actor = let actor = RepoActor::new(
RepoActor::new(repo_details, webhook.clone(), generation, net.clone(), repo); repo_details,
webhook.clone(),
generation,
net.clone(),
repo.clone(),
);
(forge_name.clone(), repo_alias, actor) (forge_name.clone(), repo_alias, actor)
} }
} }

View file

@ -13,7 +13,7 @@ fn test_name() {
panic!("fs") panic!("fs")
}; };
let net = Network::new_mock(); let net = Network::new_mock();
let repo = git::repository::mock(); let (repo, _reality) = git::repository::mock();
let repo_details = common::repo_details( let repo_details = common::repo_details(
1, 1,
Generation::new(), Generation::new(),
@ -40,7 +40,7 @@ async fn test_branches_get() {
let body = include_str!("./data-forgejo-branches-get.json"); let body = include_str!("./data-forgejo-branches-get.json");
net.add_get_response(&url, StatusCode::OK, body); net.add_get_response(&url, StatusCode::OK, body);
let net = Network::from(net); let net = Network::from(net);
let repo = git::repository::mock(); let (repo, _reality) = git::repository::mock();
let repo_details = common::repo_details( let repo_details = common::repo_details(
1, 1,

View file

@ -4,6 +4,7 @@ install-hooks:
git config core.hooksPath .git-hooks git config core.hooksPath .git-hooks
validate-dev-branch: validate-dev-branch:
git rebase -i origin/main -x 'cargo fmt --check'
git rebase -i origin/main -x 'cargo build' git rebase -i origin/main -x 'cargo build'
git rebase -i origin/main -x 'cargo test' git rebase -i origin/main -x 'cargo test'
git rebase -i origin/main -x 'cargo clippy -- -D warnings' git rebase -i origin/main -x 'cargo clippy -- -D warnings'