1pub mod receive_pack;
8pub mod upload_pack;
9
10use std::io::Read;
11use std::path::{Path, PathBuf};
12
13use grit_lib::config::git_path::path_for_error_message;
14use grit_lib::config::ConfigSet;
15
16pub use grit_lib::config::environment::RepositoryOptions;
17use grit_lib::objects::odb::Odb;
18use grit_lib::remote::serve::{
19 self, ProtocolVersion, ReceiveHook, ReceivePolicy, RefCommand, RefUpdateRefusal,
20 RefUpdateResult, ServeOptions,
21};
22use grit_lib::remote::snapshot_checkout::TargetGuard;
23use grit_lib::repo::Repository;
24
25#[derive(Debug, thiserror::Error)]
27pub enum Error {
28 #[error("not a git repository: {0}")]
30 NotARepository(String),
31 #[error(transparent)]
33 Serve(#[from] serve::ServeError),
34 #[error(transparent)]
36 Repository(#[from] grit_lib::error::Error),
37 #[error(transparent)]
39 Io(#[from] std::io::Error),
40}
41
42impl Error {
43 #[must_use]
59 pub fn request_stream_error(&self) -> Option<&std::io::Error> {
60 match self {
61 Self::Serve(serve::ServeError::Io(e)) => Some(e),
62 _ => None,
63 }
64 }
65}
66
67pub type Result<T> = std::result::Result<T, Error>;
69
70#[derive(Debug, Clone, Default)]
72pub struct Extensions {
73 pub bundle_list: Option<grit_lib::remote::bundle_uri::BundleList>,
75 pub push_bundle: Option<String>,
77}
78
79#[derive(Debug, Clone, Default)]
86pub struct PushGuard {
87 target: Option<TargetGuard>,
88}
89
90impl PushGuard {
91 #[must_use]
97 pub fn for_repository(repo: &Repository) -> Self {
98 Self {
99 target: TargetGuard::for_repository(repo),
100 }
101 }
102
103 #[must_use]
105 pub fn target(&self) -> Option<&str> {
106 self.target.as_ref().map(TargetGuard::target)
107 }
108}
109
110impl ReceiveHook for PushGuard {
111 fn update(&self, command: &RefCommand, odb: &Odb) -> std::result::Result<(), RefUpdateRefusal> {
112 self.target
113 .as_ref()
114 .map_or(Ok(()), |guard| guard.update(command, odb))
115 }
116
117 fn message(&self, updates: &[RefUpdateResult]) -> Option<String> {
118 let guard = self.target.as_ref()?;
119 updates
120 .iter()
121 .any(|u| u.error.is_some() && guard.guards(&u.refname))
122 .then(|| target_push_advice(guard.target()))
123 }
124}
125
126fn target_push_advice(target: &str) -> String {
128 format!(
129 "{target} is the server's target branch: pushes can't change it.\n\
130 Push your work to another branch:\n\
131 \x20 grit switch -c <branch>\n\
132 \x20 grit push origin <branch>\n\
133 then merge it into {target} from a snapshot checkout of this repository:\n\
134 \x20 grit integrate <branch>\n\
135 (In a snapshot checkout, `grit checkin` sends your branches and `grit integrate` merges them.)\n"
136 )
137}
138
139#[must_use]
147pub fn repository_options_from_process() -> RepositoryOptions {
148 RepositoryOptions::from_process()
149}
150
151#[must_use]
153pub fn protocol_version_from_header(version: Option<u8>) -> ProtocolVersion {
154 match version {
155 Some(2) => ProtocolVersion::V2,
156 Some(1) => ProtocolVersion::V1,
157 _ => ProtocolVersion::V0,
158 }
159}
160
161pub fn validate_repo_path(path: &Path) -> Result<PathBuf> {
167 if path.join("HEAD").is_file() {
168 return Ok(path.to_path_buf());
169 }
170 let dot_git = path.join(".git");
171 if dot_git.join("HEAD").is_file() {
172 return Ok(path.to_path_buf());
173 }
174 Err(Error::NotARepository(path_for_error_message(path)))
175}
176
177pub(crate) fn run_upload_pack(
178 repo_path: &Path,
179 protocol_version: Option<u8>,
180 stateless_rpc: bool,
181 advertise_refs: bool,
182 input: &[u8],
183 repository_options: &RepositoryOptions,
184 extensions: &Extensions,
185) -> Result<Vec<u8>> {
186 let mut output = Vec::new();
187 run_upload_pack_to(
188 repo_path,
189 protocol_version,
190 stateless_rpc,
191 advertise_refs,
192 input,
193 repository_options,
194 extensions,
195 &mut output,
196 )?;
197 Ok(output)
198}
199
200#[allow(clippy::too_many_arguments)]
201pub(crate) fn run_upload_pack_to(
202 repo_path: &Path,
203 protocol_version: Option<u8>,
204 stateless_rpc: bool,
205 advertise_refs: bool,
206 input: &[u8],
207 repository_options: &RepositoryOptions,
208 extensions: &Extensions,
209 output: &mut dyn std::io::Write,
210) -> Result<()> {
211 let without_fetcher = repository_options
212 .clone()
213 .with_promisor_fetcher(None)
214 .for_serving();
215 let repo = Repository::open(repo_path, &without_fetcher)?;
216 let config =
217 ConfigSet::load(repo.environment(), Some(repo.git_dir()), true).unwrap_or_default();
218 let hidden_refs = grit_lib::refs::hide_refs::hide_ref_patterns_uploadpack(&config);
219 let mut opts = ServeOptions {
220 protocol: protocol_version_from_header(protocol_version),
221 stateless_rpc,
222 advertise_refs,
223 agent: format!("grit/{}", env!("CARGO_PKG_VERSION")),
224 hidden_refs,
225 bundle_list: extensions.bundle_list.clone(),
226 push_bundle: None,
227 lazy_fetch: ServeOptions::lazy_fetch_from_environment(repo.environment()),
228 ..ServeOptions::default()
229 };
230 opts.attach_promisor_fetcher(&repo, &config, repository_options.promisor_fetcher.clone());
233 let _summary = serve::upload_pack(&repo, &mut &*input, output, &mut opts)?;
234 Ok(())
235}
236
237pub(crate) fn run_receive_pack(
238 repo_path: &Path,
239 stateless_rpc: bool,
240 advertise_refs: bool,
241 input: &mut dyn Read,
242 repository_options: &RepositoryOptions,
243 extensions: &Extensions,
244) -> Result<Vec<u8>> {
245 let options = repository_options
246 .clone()
247 .with_promisor_fetcher(None)
248 .for_serving();
249 let repo = Repository::open(repo_path, &options)?;
250 let config =
251 ConfigSet::load(repo.environment(), Some(repo.git_dir()), true).unwrap_or_default();
252 let hidden_refs = grit_lib::refs::hide_refs::hide_ref_patterns_receive(&config);
253 let opts = ServeOptions {
254 protocol: ProtocolVersion::V0,
255 stateless_rpc,
256 advertise_refs,
257 agent: format!("grit/{}", env!("CARGO_PKG_VERSION")),
258 hidden_refs,
259 bundle_list: None,
260 push_bundle: extensions.push_bundle.clone(),
261 ..ServeOptions::default()
262 };
263 let policy = ReceivePolicy::from_config(&config);
264 let guard = PushGuard::for_repository(&repo);
265 let mut output = Vec::new();
266 serve::receive_pack_with_hook(&repo, input, &mut output, &opts, &policy, &guard)?;
267 Ok(output)
268}
269
270#[cfg(test)]
271mod tests {
272 use super::*;
273 use grit_lib::remote::serve::ProtocolVersion;
274
275 #[test]
276 fn pushes_of_the_target_are_told_what_to_do_instead() {
277 let result = |refname: &str, error: Option<RefUpdateRefusal>| RefUpdateResult {
278 refname: refname.to_owned(),
279 old: None,
280 new: None,
281 error,
282 };
283 let refused = Some(RefUpdateRefusal::TargetBranch {
284 target: "main".to_owned(),
285 });
286 assert_eq!(
287 PushGuard::default().message(&[result("refs/heads/main", refused.clone())]),
288 None,
289 "a repository without checkouts has no guard"
290 );
291 let guard = PushGuard {
292 target: Some(TargetGuard::new("main")),
293 };
294 assert_eq!(guard.target(), Some("main"));
295 assert_eq!(guard.message(&[result("refs/heads/main", None)]), None);
296 assert_eq!(
297 guard.message(&[result(
298 "refs/heads/topic",
299 Some(RefUpdateRefusal::StaleInfo)
300 )]),
301 None
302 );
303 let advice = guard
304 .message(&[
305 result("refs/heads/topic", None),
306 result("refs/heads/main", refused),
307 ])
308 .unwrap_or_default();
309 assert!(
310 advice.starts_with("main is the server's target branch"),
311 "{advice}"
312 );
313 assert!(advice.contains("grit integrate <branch>"), "{advice}");
314 assert!(guard
316 .message(&[result(
317 "refs/heads/main",
318 Some(RefUpdateRefusal::CurrentBranch)
319 )])
320 .is_some());
321 }
322
323 #[test]
324 fn protocol_header_maps_versions() {
325 assert_eq!(protocol_version_from_header(None), ProtocolVersion::V0);
326 assert_eq!(protocol_version_from_header(Some(2)), ProtocolVersion::V2);
327 }
328}