1use std::path::Path;
23
24use sley_config::GitConfig;
25use sley_core::{ObjectFormat, Result};
26use sley_transport::GitCredential;
27
28mod install;
29pub use install::{
30 install_protocol_v2_fetch_promisor_response_from_reader,
31 install_protocol_v2_fetch_response_from_reader,
32 install_upload_pack_packfile_promisor_response_from_reader,
33 install_upload_pack_packfile_response_from_reader,
34 install_upload_pack_raw_promisor_response_from_reader,
35 install_upload_pack_raw_response_from_reader,
36 install_upload_pack_shallow_packfile_promisor_response_from_reader,
37 install_upload_pack_shallow_packfile_response_from_reader,
38 install_upload_pack_shallow_raw_promisor_response_from_reader,
39 install_upload_pack_shallow_raw_response_from_reader,
40 shallow_info_from_protocol_v2_fetch_header,
41};
42
43mod credentials;
44pub use credentials::{
45 CredentialHelperProvider, credential_fill, credential_request_for_url, credential_store,
46 http_credential_host, http_protocol_name, http_url_credential,
47};
48
49#[cfg(feature = "http")]
50mod http;
51#[cfg(feature = "http")]
52pub use http::{
53 HttpFetchPackRequest, HttpServiceAdvertisements, http_advertised_refs,
54 http_authorization_headers, http_check_status, http_protocol_v2_fetch_response,
55 http_send_with_auth, http_service_advertisements, http_upload_pack_advertisements,
56 http_upload_pack_features, http_validate_content_type,
57 install_fetch_pack_via_http_protocol_v2_fetch, install_fetch_pack_via_http_upload_pack,
58 new_http_client, HttpOperationBatch,
59 remote_url_is_http,
60};
61
62mod ssh;
63pub use ssh::{
64 SshFetchPackRequest, SshTransportOptions, install_fetch_pack_via_ssh_upload_pack, ssh_program,
65 ssh_transport_options_from_config, ssh_upload_pack_advertisements,
66 ssh_upload_pack_advertisements_with_options,
67};
68
69mod git;
70mod git_proxy;
71pub use git::{
72 GitFetchPackRequest, git_upload_pack_advertisements,
73 git_upload_pack_advertisements_with_protocol, install_fetch_pack_via_git_upload_pack,
74};
75
76mod proc_receive;
77mod receive_hooks;
78pub use receive_hooks::{run_pre_receive, run_update_hooks};
79mod receive_pack_server;
80
81pub use proc_receive::{
82 ProcReceiveRefPattern, ProcReceiveReport, ReceivePackCommandState, parse_proc_receive_refs,
83 proc_receive_ref_matches,
84};
85pub use receive_pack_server::{
86 ReceivePackServerOptions, ReceivePackServerOutcome, ReceivePackServerReport,
87 ReceivePackServerRequest, flush_receive_pack_sideband, receive_pack_server_report_v1,
88 request_uses_sideband, run_receive_pack_post_hooks, serve_receive_pack,
89 write_receive_pack_server_report, write_receive_pack_sideband_stderr,
90};
91
92mod local;
93pub use local::{
94 INFINITE_DEPTH, LocalDeepenPlan, attach_receive_pack_capabilities,
95 attach_upload_pack_capabilities, compute_local_deepen, compute_local_deepen_by_rev_list,
96 install_fetch_pack_via_local_upload_pack, local_fetch_advertisements, local_have_oids,
97 receive_pack_features, receive_pack_into_local_repository,
98 receive_pack_request_uses_push_options, receive_pack_stream_into_local_repository,
99 serve_upload_pack_v2, serve_upload_pack_v2_with_config, upload_pack_features,
100 upload_pack_from_local_repository, upload_pack_request_uses_sideband,
101 upload_pack_sideband_response,
102};
103
104mod filter;
105pub use filter::{pack_filter_from_spec, pack_filter_from_spec_for_clone};
106
107mod fetch;
108pub use fetch::{
109 FetchOptions, FetchOutcome, FetchRequest, FetchServices, FetchSource, PruneRefsInput,
110 PrunedRef, append_reachable_auto_follow_tags, apply_configured_fetch_prune_option,
111 apply_configured_partial_clone_filter, apply_configured_remote_tag_option, fetch,
112 fetch_head_source_description,
113 fetch_refspec_excludes, fetch_refspecs_for_source, mark_tag_refspec_updates_not_for_merge,
114 order_bundle_fetch_all_tags_updates, prune_refs_from_advertisements,
115 retain_missing_auto_follow_tags, write_default_fetch_head, write_fetch_head,
116 write_fetch_head_records,
117};
118
119mod pack;
120pub use pack::{
121 PushPackRequest, build_push_packfile, build_receive_pack_body,
122 remote_advertisement_tips_known_to_local,
123};
124
125mod push;
126pub use push::{
127 PushAction, PushActionPlan, PushActionRequest, PushCommand, PushDestination, PushOptions,
128 PushOutcome, PushPlan, PushQuarantine, PushRefStatus, PushReportRef, PushReportRequest,
129 PushRequest, PushServices, PushStatusReport, PushThinMode, ReceivePackPushReport,
130 apply_receive_pack_report_to_push_refs, execute_push_action_plan, execute_push_plan,
131 local_push_source_refs, normalize_push_refname, normalize_push_refspec, plan_push,
132 plan_push_actions, push, push_actions, push_local_uses_receive_pack_server,
133 push_local_with_report, run_local_push_post_hooks, push_url_for_display,
134 read_receive_pack_push_report, reject_non_fast_forward_pushes, stage_local_push_quarantine,
135 validate_receive_pack_report, validate_receive_pack_unpack,
136};
137
138mod ls_remote;
139pub use ls_remote::{LsRemoteFilter, LsRemoteRecord, LsRemoteSource, ls_remote};
140
141mod clone;
142pub use clone::{CloneOptions, CloneOutcome, CloneRequest, CloneServices, CloneSource, clone};
143
144mod bundle;
145pub use bundle::{FetchBundleRequest, fetch_bundle};
146mod bundle_uri;
147pub use bundle_uri::{
148 BundleUriEntry, BundleUriList, bundle_uri_fetch_order, handshake_advertises_bundle_uri,
149 http_remote_bundle_uri_list, parse_bundle_uri_line, prefetch_advertised_bundle_uris,
150 transfer_bundle_uri_enabled,
151};
152
153mod shallow;
154pub use shallow::{apply_shallow_info, read_shallow, write_shallow};
155
156mod capabilities;
157pub use capabilities::{RemoteTransportKind, TransportCapabilities};
158
159mod protocol;
160pub use protocol::{
161 TransportPolicyError, check_transport_allowed, is_transport_allowed,
162 transport_scheme_for_remote, transport_scheme_for_url,
163};
164
165mod resolve;
166pub use resolve::{
167 fetch_source_for_url, fetch_url, push_destination_for_url, push_url, resolve_fetch_source,
168 resolve_push_destination, transport_kind_for_url,
169};
170
171pub fn object_format_for_git_dir(common_git_dir: &Path) -> Result<ObjectFormat> {
177 let Ok(config) = GitConfig::read(common_git_dir.join("config")) else {
178 return Ok(ObjectFormat::Sha1);
179 };
180 config.repository_object_format()
181}
182
183pub trait CredentialProvider {
192 fn fill(&mut self, request: GitCredential) -> Result<Option<GitCredential>>;
195
196 fn approve(&mut self, _credential: &GitCredential) -> Result<()> {
198 Ok(())
199 }
200
201 fn reject(&mut self, _credential: &GitCredential) -> Result<()> {
203 Ok(())
204 }
205}
206
207#[derive(Debug, Default, Clone, Copy)]
211pub struct NoCredentials;
212
213impl CredentialProvider for NoCredentials {
214 fn fill(&mut self, _request: GitCredential) -> Result<Option<GitCredential>> {
215 Ok(None)
216 }
217}
218
219pub trait ProgressSink {
224 fn message(&mut self, _message: &str) {}
226}
227
228#[derive(Debug, Default, Clone, Copy)]
230pub struct SilentProgress;
231
232impl ProgressSink for SilentProgress {}
233
234#[cfg(test)]
235mod tests {
236 use super::*;
237 use std::fs;
238 use std::path::{Path, PathBuf};
239 use std::sync::atomic::{AtomicU64, Ordering};
240
241 use sley_config::{ConfigEntry, ConfigSection};
242 use sley_formats::RepositoryLayout;
243 use sley_object::{Commit, EncodedObject, ObjectType, Tree};
244 use sley_odb::{FileObjectDatabase, ObjectWriter};
245 use sley_refs::{FileRefStore, RefTarget, RefUpdate};
246 use sley_transport::{RemoteUrl, parse_remote_url};
247
248 #[test]
249 fn no_credentials_never_fills() {
250 let mut provider = NoCredentials;
251 let request = GitCredential::default();
252 assert!(
253 provider
254 .fill(request)
255 .expect("test operation should succeed")
256 .is_none()
257 );
258 }
259
260 #[test]
261 fn silent_progress_accepts_messages() {
262 let mut progress = SilentProgress;
263 progress.message("Cloning into 'x'...");
264 }
265
266 static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
267
268 fn live_env(name: &str) -> Option<String> {
269 match std::env::var(name) {
270 Ok(value) if !value.is_empty() => Some(value),
271 _ => None,
272 }
273 }
274
275 fn live_repo(name: &str) -> PathBuf {
276 let dir = std::env::temp_dir().join(format!(
277 "sley-remote-live-{name}-{}-{}",
278 std::process::id(),
279 TEMP_COUNTER.fetch_add(1, Ordering::Relaxed)
280 ));
281 let _ = fs::remove_dir_all(&dir);
282 RepositoryLayout::init_at(&dir, ObjectFormat::Sha1, false)
283 .expect("live test repository should initialize");
284 dir.join(".git")
285 }
286
287 fn remote_config(url: &str) -> GitConfig {
288 GitConfig {
289 sections: vec![ConfigSection::new(
290 "remote",
291 Some("origin".into()),
292 vec![
293 ConfigEntry::new("url", Some(url.into())),
294 ConfigEntry::new("fetch", Some("+refs/heads/*:refs/remotes/origin/*".into())),
295 ],
296 )],
297 ..GitConfig::default()
298 }
299 }
300
301 fn fetch_options(depth: Option<u32>) -> FetchOptions {
302 FetchOptions {
303 quiet: true,
304 auto_follow_tags: false,
305 fetch_all_tags: false,
306 prune: false,
307 prune_tags: false,
308 dry_run: false,
309 force: false,
310 append: false,
311 write_fetch_head: true,
312 tag_option_explicit: true,
313 prune_option_explicit: true,
314 prune_tags_option_explicit: true,
315 refmap: None,
316 depth,
317 merge_srcs: Vec::new(),
318 filter: None,
319 refetch: false,
320 cloning: false,
321 record_promisor_refs: true,
322 update_shallow: false,
323 reject_shallow: false,
324 deepen_relative: false,
325 update_head_ok: false,
326 deepen_since: None,
327 deepen_not: Vec::new(),
328 ssh_options: None,
329 atomic: false,
330 negotiation_restrict: None,
331 negotiation_include: None,
332 }
333 }
334
335 fn write_live_commit(git_dir: &Path, branch: &str) {
336 let format = ObjectFormat::Sha1;
337 let db = FileObjectDatabase::from_git_dir(git_dir, format);
338 let tree = db
339 .write_object(EncodedObject::new(
340 ObjectType::Tree,
341 Tree { entries: vec![] }.write(),
342 ))
343 .expect("live commit tree should write");
344 let timestamp = 1 + TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
345 let identity =
346 format!("Sley Remote Live <sley@example.invalid> {timestamp} +0000").into_bytes();
347 let oid = db
348 .write_object(EncodedObject::new(
349 ObjectType::Commit,
350 Commit {
351 tree,
352 parents: Vec::new(),
353 author: identity.clone(),
354 committer: identity,
355 encoding: None,
356 message: format!("sley remote live {branch}\n").into_bytes(),
357 }
358 .write(),
359 ))
360 .expect("live commit should write");
361 let store = FileRefStore::new(git_dir, format);
362 let mut tx = store.transaction();
363 tx.update(RefUpdate {
364 name: format!("refs/heads/{branch}"),
365 expected: None,
366 new: RefTarget::Direct(oid),
367 reflog: None,
368 });
369 tx.update(RefUpdate {
370 name: "HEAD".into(),
371 expected: None,
372 new: RefTarget::Symbolic(format!("refs/heads/{branch}")),
373 reflog: None,
374 });
375 tx.commit().expect("live refs should update");
376 }
377
378 struct EnvCredentials {
379 username: String,
380 password: String,
381 }
382
383 impl CredentialProvider for EnvCredentials {
384 fn fill(&mut self, mut request: GitCredential) -> Result<Option<GitCredential>> {
385 request.username = Some(self.username.clone());
386 request.password = Some(self.password.clone());
387 Ok(Some(request))
388 }
389 }
390
391 fn live_fetch(
392 url_var: &str,
393 branch_var: &str,
394 source: FetchSource,
395 credentials: &mut dyn CredentialProvider,
396 depth: Option<u32>,
397 ) {
398 let Some(url) = live_env(url_var) else {
399 return;
400 };
401 let branch = live_env(branch_var).unwrap_or_else(|| "main".into());
402 let local = live_repo(url_var);
403 let refspec = format!("refs/heads/{branch}:refs/remotes/origin/{branch}");
404 let config = remote_config(&url);
405 let options = fetch_options(depth);
406 let mut progress = SilentProgress;
407
408 let outcome = fetch(
409 FetchRequest {
410 git_dir: &local,
411 format: ObjectFormat::Sha1,
412 config: &config,
413 remote_name: "origin",
414 source: &source,
415 refspecs: &[refspec],
416 options: &options,
417 },
418 FetchServices {
419 credentials,
420 progress: &mut progress,
421 ref_hook: None,
422 },
423 )
424 .expect("live fetch should succeed");
425
426 assert!(!outcome.ref_updates.is_empty());
427 if depth.is_some() {
428 assert!(
429 local.join("shallow").exists(),
430 "shallow fetch should write .git/shallow"
431 );
432 }
433 }
434
435 fn live_push(
436 url_var: &str,
437 branch_prefix_var: &str,
438 destination: PushDestination,
439 credentials: &mut dyn CredentialProvider,
440 ) {
441 let Some(_) = live_env(url_var) else {
442 return;
443 };
444 let branch_prefix =
445 live_env(branch_prefix_var).unwrap_or_else(|| "sley-remote-live".into());
446 let branch = format!(
447 "{branch_prefix}-{}-{}",
448 std::process::id(),
449 TEMP_COUNTER.fetch_add(1, Ordering::Relaxed)
450 );
451 let local = live_repo(url_var);
452 write_live_commit(&local, &branch);
453 let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
454 let options = PushOptions {
455 quiet: true,
456 force: false,
457 thin: PushThinMode::Auto,
458 };
459 let mut progress = SilentProgress;
460
461 let outcome = push(
462 PushRequest {
463 git_dir: &local,
464 common_git_dir: &local,
465 format: ObjectFormat::Sha1,
466 config: &GitConfig::default(),
467 remote: "origin",
468 destination: &destination,
469 refspecs: &[refspec],
470 options: &options,
471 },
472 PushServices {
473 credentials,
474 progress: &mut progress,
475 },
476 )
477 .expect("live push should succeed");
478
479 assert_eq!(outcome.commands.len(), 1);
480 }
481
482 #[test]
483 fn live_github_https_public_fetch() {
484 let Some(url) = live_env("SLEY_REMOTE_LIVE_GITHUB_HTTPS_PUBLIC_URL") else {
485 return;
486 };
487 let remote = parse_remote_url(&url).expect("live HTTPS URL should parse");
488 let mut credentials = NoCredentials;
489 live_fetch(
490 "SLEY_REMOTE_LIVE_GITHUB_HTTPS_PUBLIC_URL",
491 "SLEY_REMOTE_LIVE_GITHUB_HTTPS_PUBLIC_BRANCH",
492 FetchSource::Http(remote),
493 &mut credentials,
494 None,
495 );
496 }
497
498 #[test]
499 fn live_private_https_auth_fetch_uses_credential_provider() {
500 let (Some(url), Some(username), Some(password)) = (
501 live_env("SLEY_REMOTE_LIVE_PRIVATE_HTTPS_URL"),
502 live_env("SLEY_REMOTE_LIVE_PRIVATE_HTTPS_USERNAME"),
503 live_env("SLEY_REMOTE_LIVE_PRIVATE_HTTPS_PASSWORD"),
504 ) else {
505 return;
506 };
507 let remote = parse_remote_url(&url).expect("live private HTTPS URL should parse");
508 let mut credentials = EnvCredentials { username, password };
509 live_fetch(
510 "SLEY_REMOTE_LIVE_PRIVATE_HTTPS_URL",
511 "SLEY_REMOTE_LIVE_PRIVATE_HTTPS_BRANCH",
512 FetchSource::Http(remote),
513 &mut credentials,
514 None,
515 );
516 }
517
518 #[test]
519 fn live_https_push() {
520 let Some(url) = live_env("SLEY_REMOTE_LIVE_HTTPS_PUSH_URL") else {
521 return;
522 };
523 let remote = parse_remote_url(&url).expect("live HTTPS push URL should parse");
524 let mut no_credentials;
525 let mut env_credentials;
526 let credentials: &mut dyn CredentialProvider = match (
527 live_env("SLEY_REMOTE_LIVE_HTTPS_PUSH_USERNAME"),
528 live_env("SLEY_REMOTE_LIVE_HTTPS_PUSH_PASSWORD"),
529 ) {
530 (Some(username), Some(password)) => {
531 env_credentials = EnvCredentials { username, password };
532 &mut env_credentials
533 }
534 _ => {
535 no_credentials = NoCredentials;
536 &mut no_credentials
537 }
538 };
539 live_push(
540 "SLEY_REMOTE_LIVE_HTTPS_PUSH_URL",
541 "SLEY_REMOTE_LIVE_HTTPS_PUSH_BRANCH_PREFIX",
542 PushDestination::Http(remote),
543 credentials,
544 );
545 }
546
547 #[test]
548 fn live_ssh_fetch() {
549 let Some(url) = live_env("SLEY_REMOTE_LIVE_SSH_FETCH_URL") else {
550 return;
551 };
552 let remote = parse_remote_url(&url).expect("live SSH fetch URL should parse");
553 let mut credentials = NoCredentials;
554 live_fetch(
555 "SLEY_REMOTE_LIVE_SSH_FETCH_URL",
556 "SLEY_REMOTE_LIVE_SSH_FETCH_BRANCH",
557 FetchSource::Ssh(remote),
558 &mut credentials,
559 None,
560 );
561 }
562
563 #[test]
564 fn live_ssh_push() {
565 let Some(url) = live_env("SLEY_REMOTE_LIVE_SSH_PUSH_URL") else {
566 return;
567 };
568 let remote = parse_remote_url(&url).expect("live SSH push URL should parse");
569 let mut credentials = NoCredentials;
570 live_push(
571 "SLEY_REMOTE_LIVE_SSH_PUSH_URL",
572 "SLEY_REMOTE_LIVE_SSH_PUSH_BRANCH_PREFIX",
573 PushDestination::Ssh(remote),
574 &mut credentials,
575 );
576 }
577
578 #[test]
579 fn live_shallow_https_fetch_and_clone() {
580 let Some(url) = live_env("SLEY_REMOTE_LIVE_SHALLOW_HTTPS_URL") else {
581 return;
582 };
583 let branch =
584 live_env("SLEY_REMOTE_LIVE_SHALLOW_HTTPS_BRANCH").unwrap_or_else(|| "main".into());
585 let remote = parse_remote_url(&url).expect("live shallow HTTPS URL should parse");
586 let mut credentials = NoCredentials;
587 live_fetch(
588 "SLEY_REMOTE_LIVE_SHALLOW_HTTPS_URL",
589 "SLEY_REMOTE_LIVE_SHALLOW_HTTPS_BRANCH",
590 FetchSource::Http(remote.clone()),
591 &mut credentials,
592 Some(1),
593 );
594
595 let destination = std::env::temp_dir().join(format!(
596 "sley-remote-live-clone-{}-{}",
597 std::process::id(),
598 TEMP_COUNTER.fetch_add(1, Ordering::Relaxed)
599 ));
600 let _ = fs::remove_dir_all(&destination);
601 let config = remote_config(&url);
602 let mut configure = |_git_dir: &Path| Ok(config.clone());
603 let mut configure_branch = |_git_dir: &Path, _branch: &str| Ok(config.clone());
604 let options = CloneOptions {
605 origin: "origin",
606 checkout_branch: &branch,
607 remote_head_branch: &branch,
608 single_branch: true,
609 depth: Some(1),
610 deepen_since: None,
611 deepen_not: Vec::new(),
612 committer: b"Sley Remote Live <sley@example.invalid> 1 +0000".to_vec(),
613 detached_head: None,
614 checkout: true,
615 filter: None,
616 branch_explicit: true,
619 ref_storage: sley_formats::RefStorageFormat::Files,
620 ssh_options: None,
621 reject_shallow: false,
622 };
623 let mut clone_credentials = NoCredentials;
624 let mut progress = SilentProgress;
625
626 let outcome = clone(
627 CloneRequest {
628 destination: &destination,
629 git_dir_override: None,
630 core_worktree: None,
631 format: ObjectFormat::Sha1,
632 source: &CloneSource::Http(RemoteUrl { ..remote }),
633 options: &options,
634 },
635 CloneServices {
636 configure: &mut configure,
637 configure_branch: &mut configure_branch,
638 credentials: &mut clone_credentials,
639 progress: &mut progress,
640 },
641 )
642 .expect("live shallow HTTPS clone should succeed");
643
644 assert!(outcome.git_dir.join("shallow").exists());
645 }
646}