pub mod receive_pack;
pub mod session;
pub mod upload_pack;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use grit_lib::config::git_path::path_for_error_message;
use grit_lib::config::ConfigSet;
pub use grit_lib::config::environment::RepositoryOptions;
use grit_lib::objects::odb::Odb;
use grit_lib::remote::serve::{
self, ProtocolVersion, ReceiveHook, ReceiveHookContext, ReceiveOutcome, ReceivePolicy,
RefCommand, RefUpdateRefusal, RefUpdateResult, ServeOptions, UploadOutcome,
};
use grit_lib::remote::snapshot_checkout::TargetGuard;
use grit_lib::repo::Repository;
pub use session::{ReceiveRpcResult, ServeSession};
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("not a git repository: {0}")]
NotARepository(String),
#[error(transparent)]
Serve(#[from] serve::ServeError),
#[error(transparent)]
Repository(Box<grit_lib::error::Error>),
#[error(transparent)]
Io(#[from] std::io::Error),
}
impl Error {
#[must_use]
pub fn request_stream_error(&self) -> Option<&std::io::Error> {
match self {
Self::Serve(serve::ServeError::Io(e)) => Some(e),
_ => None,
}
}
}
impl From<grit_lib::error::Error> for Error {
fn from(value: grit_lib::error::Error) -> Self {
match value {
grit_lib::error::Error::Remote(grit_lib::remote::RemoteError::Serve(serve)) => {
Self::Serve(serve)
}
grit_lib::error::Error::Io(io) => Self::Serve(serve::ServeError::Io(io)),
other => Self::Repository(Box::new(other)),
}
}
}
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Clone, Default)]
pub struct Extensions {
pub bundle_list: Option<grit_lib::remote::bundle_uri::BundleList>,
pub push_bundle: Option<String>,
}
#[derive(Debug, Clone, Default)]
pub struct PushGuard {
target: Option<TargetGuard>,
}
impl PushGuard {
#[must_use]
pub fn for_repository(repo: &Repository) -> Self {
Self {
target: TargetGuard::for_repository(repo),
}
}
#[must_use]
pub fn target(&self) -> Option<&str> {
self.target.as_ref().map(TargetGuard::target)
}
}
impl ReceiveHook for PushGuard {
fn update(&self, command: &RefCommand, odb: &Odb) -> std::result::Result<(), RefUpdateRefusal> {
self.target
.as_ref()
.map_or(Ok(()), |guard| guard.update(command, odb))
}
fn message(&self, updates: &[RefUpdateResult]) -> Option<String> {
let guard = self.target.as_ref()?;
updates
.iter()
.any(|u| u.error.is_some() && guard.guards(&u.refname))
.then(|| target_push_advice(guard.target()))
}
}
struct GuardedHook {
guard: PushGuard,
extra: Option<std::sync::Arc<dyn ReceiveHook + Send + Sync>>,
}
impl ReceiveHook for GuardedHook {
fn pre_receive_ctx(
&self,
commands: &[RefCommand],
odb: &Odb,
ctx: &ReceiveHookContext<'_>,
) -> std::result::Result<(), RefUpdateRefusal> {
self.guard.pre_receive_ctx(commands, odb, ctx)?;
if let Some(h) = self.extra.as_deref() {
h.pre_receive_ctx(commands, odb, ctx)?;
}
Ok(())
}
fn update_ctx(
&self,
command: &RefCommand,
odb: &Odb,
ctx: &ReceiveHookContext<'_>,
) -> std::result::Result<(), RefUpdateRefusal> {
self.guard.update_ctx(command, odb, ctx)?;
if let Some(h) = self.extra.as_deref() {
h.update_ctx(command, odb, ctx)?;
}
Ok(())
}
fn message(&self, updates: &[RefUpdateResult]) -> Option<String> {
match (
self.guard.message(updates),
self.extra.as_deref().and_then(|h| h.message(updates)),
) {
(None, None) => None,
(Some(a), None) => Some(a),
(None, Some(b)) => Some(b),
(Some(a), Some(b)) => Some(format!("{a}{b}")),
}
}
fn post_receive(
&self,
commands: &[&RefCommand],
odb: &Odb,
ctx: &ReceiveHookContext<'_>,
) -> std::result::Result<(), RefUpdateRefusal> {
if let Some(h) = self.extra.as_deref() {
h.post_receive(commands, odb, ctx)?;
}
Ok(())
}
fn post_update(
&self,
commands: &[&RefCommand],
odb: &Odb,
) -> std::result::Result<(), RefUpdateRefusal> {
if let Some(h) = self.extra.as_deref() {
h.post_update(commands, odb)?;
}
Ok(())
}
}
fn target_push_advice(target: &str) -> String {
format!(
"{target} is the server's target branch: pushes can't change it.\n\
Push your work to another branch:\n\
\x20 grit switch -c <branch>\n\
\x20 grit push origin <branch>\n\
then merge it into {target} from a snapshot checkout of this repository:\n\
\x20 grit integrate <branch>\n\
(In a snapshot checkout, `grit checkin` sends your branches and `grit integrate` merges them.)\n"
)
}
#[must_use]
pub fn repository_options_from_process() -> RepositoryOptions {
RepositoryOptions::from_process()
}
#[must_use]
pub fn protocol_version_from_header(version: Option<u8>) -> ProtocolVersion {
match version {
Some(2) => ProtocolVersion::V2,
Some(1) => ProtocolVersion::V1,
_ => ProtocolVersion::V0,
}
}
pub fn validate_repo_path(path: &Path) -> Result<PathBuf> {
if path.join("HEAD").is_file() {
return Ok(path.to_path_buf());
}
let dot_git = path.join(".git");
if dot_git.join("HEAD").is_file() {
return Ok(path.to_path_buf());
}
Err(Error::NotARepository(path_for_error_message(path)))
}
pub(crate) fn run_upload_pack(
repo_path: &Path,
protocol_version: Option<u8>,
stateless_rpc: bool,
advertise_refs: bool,
input: &[u8],
repository_options: &RepositoryOptions,
extensions: &Extensions,
) -> Result<Vec<u8>> {
let mut output = Vec::new();
run_upload_pack_to(
repo_path,
protocol_version,
stateless_rpc,
advertise_refs,
&mut &*input,
repository_options,
extensions,
&mut output,
)?;
Ok(output)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn run_upload_pack_to(
repo_path: &Path,
protocol_version: Option<u8>,
stateless_rpc: bool,
advertise_refs: bool,
input: &mut dyn Read,
repository_options: &RepositoryOptions,
extensions: &Extensions,
output: &mut dyn std::io::Write,
) -> Result<()> {
run_upload_pack_with_session(
repo_path,
protocol_version,
stateless_rpc,
advertise_refs,
input,
repository_options,
extensions,
output,
&ServeSession::none(),
)
.map(|_| ())
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn run_upload_pack_with_session(
repo_path: &Path,
protocol_version: Option<u8>,
stateless_rpc: bool,
advertise_refs: bool,
input: &mut dyn Read,
repository_options: &RepositoryOptions,
extensions: &Extensions,
output: &mut dyn std::io::Write,
session: &ServeSession,
) -> Result<UploadOutcome> {
let without_fetcher = repository_options
.clone()
.with_promisor_fetcher(None)
.for_serving();
let repo = Repository::open(repo_path, &without_fetcher)?;
let config = ConfigSet::load(
repo.environment(),
Some(repo.git_dir()),
&grit_lib::config::LoadConfigOptions::standard(repo.environment(), Some(repo.git_dir())),
)
.unwrap_or_default();
let hidden_refs = grit_lib::refs::hide_refs::hide_ref_patterns_uploadpack(&config);
let mut opts = ServeOptions {
protocol: protocol_version_from_header(protocol_version),
stateless_rpc,
advertise_refs,
agent: format!("grit/{}", env!("CARGO_PKG_VERSION")),
hidden_refs,
bundle_list: extensions.bundle_list.clone(),
push_bundle: None,
lazy_fetch: ServeOptions::lazy_fetch_from_environment(repo.environment()),
..ServeOptions::default()
};
opts.attach_promisor_fetcher(&repo, repository_options.promisor_fetcher.clone());
serve::UploadPack::new(&repo, &mut opts)
.with_cancel(session.cancel())
.run(input, output)
.map_err(Error::from)
}
pub(crate) fn run_receive_pack(
repo_path: &Path,
stateless_rpc: bool,
advertise_refs: bool,
input: &mut dyn Read,
repository_options: &RepositoryOptions,
extensions: &Extensions,
) -> Result<Vec<u8>> {
let mut output = Vec::new();
run_receive_pack_to(
repo_path,
stateless_rpc,
advertise_refs,
input,
repository_options,
extensions,
&mut output,
)?;
Ok(output)
}
pub(crate) fn run_receive_pack_to(
repo_path: &Path,
stateless_rpc: bool,
advertise_refs: bool,
input: &mut dyn Read,
repository_options: &RepositoryOptions,
extensions: &Extensions,
output: &mut dyn Write,
) -> Result<()> {
run_receive_pack_with_session(
repo_path,
stateless_rpc,
advertise_refs,
input,
repository_options,
extensions,
output,
&ServeSession::none(),
)
.map(|_| ())
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn run_receive_pack_with_session(
repo_path: &Path,
stateless_rpc: bool,
advertise_refs: bool,
input: &mut dyn Read,
repository_options: &RepositoryOptions,
extensions: &Extensions,
output: &mut dyn Write,
session: &ServeSession,
) -> Result<ReceiveOutcome> {
let options = repository_options
.clone()
.with_promisor_fetcher(None)
.for_serving();
let repo = Repository::open(repo_path, &options)?;
let config = ConfigSet::load(
repo.environment(),
Some(repo.git_dir()),
&grit_lib::config::LoadConfigOptions::standard(repo.environment(), Some(repo.git_dir())),
)
.unwrap_or_default();
let hidden_refs = grit_lib::refs::hide_refs::hide_ref_patterns_receive(&config);
let opts = ServeOptions {
protocol: ProtocolVersion::V0,
stateless_rpc,
advertise_refs,
agent: format!("grit/{}", env!("CARGO_PKG_VERSION")),
hidden_refs,
bundle_list: None,
push_bundle: extensions.push_bundle.clone(),
..ServeOptions::default()
};
let policy = ReceivePolicy::from_config(&config);
let guard = PushGuard::for_repository(&repo);
let hook = GuardedHook {
guard,
extra: session.receive_hook.clone(),
};
serve::ReceivePack::new(&repo, &opts, &policy)
.with_hook(&hook)
.with_cancel(session.cancel())
.run(input, output)
.map_err(Error::from)
}
#[cfg(test)]
mod tests {
use super::*;
use grit_lib::remote::serve::ProtocolVersion;
#[test]
fn pushes_of_the_target_are_told_what_to_do_instead() {
let result = |refname: &str, error: Option<RefUpdateRefusal>| RefUpdateResult {
refname: refname.to_owned(),
old: None,
new: None,
error,
};
let refused = Some(RefUpdateRefusal::TargetBranch {
target: "main".to_owned(),
});
assert_eq!(
PushGuard::default().message(&[result("refs/heads/main", refused.clone())]),
None,
"a repository without checkouts has no guard"
);
let guard = PushGuard {
target: Some(TargetGuard::new("main")),
};
assert_eq!(guard.target(), Some("main"));
assert_eq!(guard.message(&[result("refs/heads/main", None)]), None);
assert_eq!(
guard.message(&[result(
"refs/heads/topic",
Some(RefUpdateRefusal::StaleInfo)
)]),
None
);
let advice = guard
.message(&[
result("refs/heads/topic", None),
result("refs/heads/main", refused),
])
.unwrap_or_default();
assert!(
advice.starts_with("main is the server's target branch"),
"{advice}"
);
assert!(advice.contains("grit integrate <branch>"), "{advice}");
assert!(guard
.message(&[result(
"refs/heads/main",
Some(RefUpdateRefusal::CurrentBranch)
)])
.is_some());
}
#[test]
fn protocol_header_maps_versions() {
assert_eq!(protocol_version_from_header(None), ProtocolVersion::V0);
assert_eq!(protocol_version_from_header(Some(2)), ProtocolVersion::V2);
}
}