Network operations in grit-lib center on Remote: a typed URL (RemoteUrl), configured fetch refspecs, and one dispatcher for fetch, push, and list refs. Wire bytes still flow through the same fetch/push engines as before; Remote picks the transport from the URL scheme.
Remote URL and config
| Scheme / form | RemoteUrl variant |
Transport |
|---|---|---|
Path or file:// |
Local / File |
in-process object copy (TransferEndpoint::Local) |
git:// |
Git |
GitDaemonTransport |
ssh://, scp-style |
Ssh |
SshTransport (repo CommandRunner) |
http(s):// |
Http / Https |
SmartHttpTransport (TransferEndpoint::Http) |
When you already hold the transport — a repository path on this machine, an open Connection, or a smart-HTTP URL with your own HttpClient — fetch and push through RepositoryRemotes::fetch_from and RepositoryRemotes::push_to with a TransferEndpoint. They run the same engines as fetch and push (refspecs, tags, prune, shallow, the same outcomes) but skip URL resolution and the client-side pre-push hook.
Parse a literal URL with RemoteUrl::try_from. Load remote.<name>.url, optional pushurl, and fetch refspecs (default +refs/heads/*:refs/remotes/<name>/*) via Remote::from_config. Config applies url.*.insteadOf and url.*.pushInsteadOf rewrite rules the same way Git does.
Local paths resolve through resolve_local_remote_git_dir from the repository root, not the process cwd.
A local or file:// fetch or push copies the same objects the wire protocol would: those reachable from the requested refs that the receiver lacks. Other branches, hidden refs, excluded tags and unreachable leftovers stay behind even when they share a pack with what was asked for. When a source pack holds only objects the transfer must send, grit hard-links it instead of rebuilding it, and it builds a pack for the rest. The send set comes from the source's reachability bitmap when it has one. The one exception is a clone from a plain path (not a file:// URL): like git clone --local, it links the source's packfiles as they are, unreachable objects included (FetchOptions::link_source_objects).
To turn a user's repository argument (a configured name, a URL, an scp-style host:path, or a path) into a Remote, call resolve_remote_argument. A configured name wins. A name with a config section but no URL fails with RemoteError::NoUrl, and anything else fails with RemoteError::UnknownRemote. grit fetch, grit pull and grit remote refs all resolve their argument this way.
Managing remotes
repo.remotes().configured() lists every remote with a remote.<name>.* section, sorted by name, the same set git remote prints. Each ConfiguredRemote carries its URL, or None when the section has no URL, plus raw push_urls, fetch_refspecs, and effective fetch/push URLs after url.*.insteadOf / pushInsteadOf. list() returns only the names that have a URL.
repo.remotes().add(name, url) writes remote.<name>.url and the default fetch refspec to the shared repository config (also from a linked worktree), then reloads the repository's config. Like git remote add, it refuses an existing remote (RemoteError::RemoteExists) and a name whose tracking refs refs/remotes/<name>/… would be invalid (RemoteError::InvalidRemoteName), and it stores the URL as given.
repo.remotes().set_url(name, url, kind, dry_run) updates fetch or push URLs on an existing remote (RemoteUrlKind::Fetch or Push), returning UrlChange. Push replaces every pushurl with one value. Returns RemoteError::UnknownRemote when the section is missing.
repo.remotes().prune(name, dry_run, http_factory) deletes stale remote-tracking refs without fetching, using the same stale-ref rules as fetch prune. Returns the full ref names removed (or that would be removed when dry_run is true).
repo.remotes().set_head(name, mode, dry_run, http_factory) sets or deletes refs/remotes/<name>/HEAD via SetHead (Auto, Branch, or Delete).
repo.remotes().inspect(name, options, http_factory) returns a RemoteSummary: fetch and push URLs, optional head_branch, RemoteBranchState rows (tracked, new, or stale), and RemotePullBranch entries from branch.* config. With InspectOptions::query it lists refs on the remote (symrefs included) and compares them to local tracking refs; stale detection uses the same rules as fetch prune. Without a query, branch names come from refs/remotes/<name>/… and are all reported as tracked.
list refs
Remote::list_refs takes ListRefsOptions (prefixes, heads, tags, symrefs, peel) and returns RemoteRef entries in git ls-remote order. On disk it scans the repository's refs directly; repo.remotes().ls_remote(remote, options, http_factory) does the same with relative paths resolved from this repository. Over the wire it uses protocol v2 ls-refs when available, otherwise the v0/v1 ref advertisement.
With peel set, annotated tags come back as two entries, the tag and a <tag>^{} line holding the object it peels to: the first non-tag object, through any chain of tags of tags, as git ls-remote reports it. RemoteRef::peeled_tag identifies those lines, and fold_peeled_refs folds them into one PeeledRemoteRef per ref, with peeled set, keeping the listing order.
Fetch and push
Remote::fetch accepts FetchOptions and a ProgressSink; fetch negotiates protocol v2 when the server supports it. Negotiation offers every local branch, remote-tracking ref, tag and HEAD as a starting point and walks local history only as far as each round needs: 16 haves first, then twice as many per round, stopping as soon as the server is ready to send the pack. An incremental fetch whose new commits build on local history reads only the newest local commits, not the whole history. Its FetchOutcome holds one RefUpdate per matched ref, including the ones that were already up to date. For a report, reported_updates keeps the refs that changed or were refused, changed_ref_count counts the changed ones, and has_rejections says whether any update was refused (UpdateMode::is_rejected). UpdateMode::kind folds each update's detailed mode into an UpdateKind (new, fast-forward, forced, pruned, rejected or up to date) for display. grit fetch builds its output and exit code from these. Remote::push uses PushRefSpec and returns PushOutcome; has_updates says whether any remote ref changed (or would, on a dry run) and has_rejections whether any update was refused, which is how grit push decides its exit code. Before it sends anything, on every transport and for dry runs too, Remote::push runs the repository's pre-push hook through RepositoryHooks::run_pre_push with one PrePushRef per update it would make; a hook that exits non-zero fails the push with Error::Hook and leaves the remote untouched. Set PushOptions::no_verify to skip it. The lower-level RepositoryRemotes::push_to never runs pre-push. A local or file:// push (including push_to with TransferEndpoint::Local) runs the remote repository's receive hooks (pre-receive, update, post-receive, post-update) the way ReceivePack does, puts their output in PushOutcome::remote_messages and reports a declined update as PushRefStatus::RemoteRejected.
A push never holds its packfile in memory. write_pack_for_push streams the pack into the connection (ssh, git://) or, when the server advertises a resumable pushBundle endpoint, into the bundle file on disk. Over plain smart HTTP a receive-pack body larger than 1 MiB (Git's default http.postBuffer) is sent with chunked transfer encoding while the pack is still being written. A small probe request goes first so any authentication challenge is answered before the large body, as Git does. A custom HttpClient should override post_streaming; the default buffers the body.
A local push applies the same ref-update checks as ReceivePack (policy, hidden refs, fast-forward rules) before it copies objects or moves refs on a path remote.
To plan a push the way grit push does, start from its positionals: resolve_push_invocation splits [<remote>] [<refspec>...] into a PushInvocation (configured remote, literal URL or path, or refspecs for the default remote). repo.remotes().push_plan_context reads the selected remote's refs (Remote::list_push_refs, one scan of the push destination) into a PushPlanContext, repo.remotes().resolve_push turns a PushRequest into concrete ref updates, and open_push_destination opens the Remote to send them to. Pass PushPlanContext::remote_tips on as PushOptions::remote_ref_tips so a local push does not scan the destination's refs a second time. The same handle turns --force / --force-with-lease into a ForceMode (force_mode), adds --follow-tags refspecs (follow_tag_push_specs), leases one ref against its tracking ref (apply_tracking_lease), and writes -u upstream config after a push (set_upstream_after_push).
pull is the high-level fetch-and-integrate operation. Build PullOptions (including shared FetchOptions, explicit refspec/FETCH_HEAD integration, resolve_pull_autostash, and dry-run --check via PullCheck), pass a progress sink and HTTP client factory, and receive a typed PullOutcome. It maps branch.<name>.merge through the remote's fetch refspecs, uses resolve_pull_integration_base after explicit fetches, skips the fetch for a local remote = . upstream, and fast-forwards, merges, or adopts the upstream on an unborn branch. Failures are typed as PullError; grit pull only builds options, invokes this API, and renders the outcome.
Unreachable remotes
When the remote cannot be talked to at all, every operation (list_refs, fetch, push, clone, pull) and every transport fails with RemoteError::Unreadable (surfaced as Error::Remote). It carries the redacted URL or resolved path and a RemoteUnreadableReason:
| Reason | When |
|---|---|
RepositoryNotFound |
A local path or file:// URL that is missing or not a Git directory (valid HEAD, objects/ and refs/, as Git checks). Listing refs never treats it as an empty remote. A linked worktree or --separate-git-dir checkout is followed through its .git file and works as a remote. |
Transport { detail } |
DNS, refused or reset connection, TLS, or timeout (HTTP and git://). Usually worth a retry. |
HttpStatus { status } |
A smart-HTTP error status such as 403, 404 or 5xx. A 401 challenge is RemoteError::Auth instead. |
NotGitServer { status, content_type } |
HTTP succeeded but the body was not a Git advertisement (for example 200 text/html from a mistyped or parked host). |
NoHandshake |
The transport ran but never spoke Git, for example ssh failed to connect, a git:// peer hung up before any pkt-line, or the ref advertisement ended at EOF without a flush. An empty remote that sends only a flush pkt-line (0000) is a completed handshake with no refs. |
Both the umbrella and the area error answer the same question: Error::is_remote_unreadable and RemoteError::is_remote_unreadable. The grit CLI maps all of them to exit code 128 and kind: remote_unreadable (Exit codes).
A remote that was reached but aborts the conversation itself fails with RemoteError::Fatal instead. Its message is the server's own text, from an ERR packet (for example upload-pack: not our ref <oid> when a fetch wants an object the server will not send) or from side-band channel 3. Every reader of upload-pack output reports it the same way, over every transport: the ref advertisement (including smart-HTTP info/refs discovery), ls-refs, negotiation, and the pack stream. Show the message to the user, but don't parse it, because each server words it differently.
HTTP remotes need an HttpClient. Implement HttpClientFactory or, with the http-ureq feature, pass None to use the default ureq-backed factory (UreqHttpClient + HelperCredentialProvider). The grit binary on macOS enables http-ureq-native-tls (Secure Transport) for HTTPS throughput; other platforms use rustls unless you opt into http-ureq-native-tls when depending on grit-lib.
With http-ureq, HTTPS uses the OS certificate store by default (RootCerts::PlatformVerifier). Git's TLS knobs apply per request URL: http.sslVerify (and scoped http.<url>.sslVerify), http.sslCAInfo, http.sslCAPath, http.sslCert, http.sslKey, and http.sslBackend, with env overrides GIT_SSL_NO_VERIFY, GIT_SSL_CAINFO, GIT_SSL_CAPATH, GIT_SSL_CERT, and GIT_SSL_KEY. Pass an Environment into UreqHttpClient::from_config so path expansion and GIT_SSL_* match Git; DefaultHttpClientFactory::with_environment does this for the CLI.
Credentials and progress
HelperCredentialProvider satisfies HTTP 401 responses from configured credential.helper programs, then from the askpass program set with with_askpass, and never opens a TTY. Askpass resolution follows Git (GIT_ASKPASS, core.askPass, SSH_ASKPASS) from an Environment you pass in; the default factory reads only core.askPass unless you build it with DefaultHttpClientFactory::with_environment (with the http-ureq feature). helpers_for lists the helpers it would run for a credential, so you can tell up front whether storing one would be a no-op. When neither the helpers nor askpass can supply a credential, fill returns RemoteError::CredentialsUnavailable with the helpers it asked, and the transport reports AuthFailure::CredentialsUnavailable carrying the same list, so a caller can tell "no helper configured" from "the helper has nothing for this host". To save a user name and token a person gives you for any host, build the credential with Credential::from_url (described below), set its username and password, and approve it; grit auth <url> --username … --token … does exactly that.
Best-effort requests whose failure is ignored, such as the advertisement push_plan_context reads and the bundle a clone tries first, use HttpClientFactory::create_for_preflight: those clients never reject a refused credential, so the push or fetch that follows sends it, reports AuthFailure::Rejected, and erases it as Git does. Every factory implements create_for_preflight; one whose clients never reject (or carry no credentials) can return the same client as create.
After an authenticated retry, HelperCredentialProvider (and any custom CredentialProvider, which must be Send + Sync) runs reject only when the server still answers 401; a typo, missing repository, permission denial or server error (403, 404, 429, 5xx) leaves the stored credential untouched.
The HTTP client asks for credentials the way Git does: Credential::from_url turns the repository URL into protocol and host, adding the repository path only when credential.useHttpPath applies, so a host-level entry from git-credential-store or a keychain helper serves every repository on the host. The full URL stays in Credential::url for matching credential.<url>.helper, and HelperCredentialProvider never sends it to a helper. A user:password@ in the URL fills the username and password (and is removed from Credential::url), so wrong URL credentials fail as AuthFailure::Rejected. Complete URL credentials are also kept in the client's in-memory origin cache so later requests to the same scheme, host and port (such as a bundle-uri download with no userinfo) send the same Authorization header without writing secrets into a helper or resumable state files.
The GitHub OAuth device flow (remote::github_auth::DeviceFlow) that grit auth uses, and the grit-server login, share, space and snapshot-checkout clients (remote::grit_server_*, remote::snapshot_checkout), exist only with the off-by-default unstable-hosting feature. They are outside the semver promise and may change in any release, so pin an exact grit-lib version if you enable it.
Whenever you show a remote address, in errors or in success output, strip embedded userinfo with redact_url_for_display so passwords never reach logs or JSON; it leaves the rest of the URL, and local paths, exactly as given. Keep the original URL for the transport and for config. Pass NullProgress to ignore sideband progress, or override ProgressSink::message for side-band channel 2. Set FetchOptions remote_progress to omit no-progress on the wire so the remote may emit channel 2; decode chunks with SidebandLines into RemoteLine updates and lines.
Fetch and clone spool the received pack to a temp file and index it in place with ingest_received_pack_path, keeping the pack instead of exploding it into loose objects. Memory does not grow with the pack size. The sequential passes (trailer checksum and object scan) read through a memory map whose resident pages are dropped every few megabytes, and delta resolution reads each compressed object from the file. A thin pack (ref-deltas against objects the receiver already has, which Git servers send on incremental fetches) is completed the way git index-pack --fix-thin does it. The missing bases are appended to the file, the object count and trailing checksum are rewritten, and the pack and its .idx are named after the new checksum. On git/git (325 MB pack, 420k objects), indexing peaks at about 80 MB, against 63 MB for git index-pack on the same file.
A received pack's length in bytes is not known until it ends, so byte counts alone cannot say how far a transfer is. Return true from ProgressSink::wants_received_objects and the receive also counts the pack's objects on a background thread, reporting ReceivedObjects (received, total from the pack header, and deltas so far) through ProgressSink::received_objects. The counting never makes the receive wait; if it falls far behind a very fast transfer, it stops. The same object-counting logic also exists as a crate-internal pack stream scanner for other callers. To turn the phases of a fetch or clone into one percentage and time-left figure, feed the same events to an OverallEstimator; it takes elapsed time as an argument rather than reading the clock.
Partial clone and promisor fetch
Filtered fetch and clone record a promisor remote (remote.<name>.promisor, extensions.partialclone, and remote.<name>.partialclonefilter). Blobs omitted from the initial pack are promised: they appear in the object database as missing until fetched on demand.
Install a PromisorFetcher on RepositoryOptions::with_promisor_fetcher (no global state). The default DefaultPromisorFetcher sends want lines for the missing object ids with filter blob:none (as Git does), does not update refs, and ingests the reply as a promisor pack. It asks the promisor remotes one after another in lazy_fetch_order: config order with the extensions.partialClone remote last, each for what is still missing, moving on when one fails. A server refuses a whole request when it lacks one of the objects, so when a remote failed and several objects are still missing, the rest is split in halves that go through the remotes again: a large-object promisor that holds only the large blobs and origin holding the small ones serve one checkout between them. A remote that cannot be used at all (unreachable, no usable URL, authentication failed) is not asked again. When objects stay missing, the error is ObjectError::PromisorFetchFailed, naming each remote that failed with a summary of its first error, or ObjectError::PromisedMissing when every remote answered without the object. The grit CLI installs this fetcher for every opened repository.
When a fetcher is installed and fetch.promisorLazy is true (the default), an ODB read miss in a partial-clone repository triggers an isolated fetch (with recursion protection) and retries the read. With no fetcher, or when lazy fetch is disabled, reads return ObjectError::PromisedMissing. Set fetch.promisorLazy=false in config, or GRIT_NO_LAZY_FETCH=1 / GIT_NO_LAZY_FETCH=1 in the environment, to opt out.
Repository::prefetch_promised batch-fetches object ids before bulk reads. Tree-to-tree checkout (including clone checkout and grit switch) collects missing blob oids from the diff and prefetches them in a single request when a fetcher is present. Hard reset also batches materialization and repair of unchanged paths, including an empty worktree/index after a metadata-only clone. Its batch includes required attribute blobs before attribute resolution, deduplicates shared blob ids, and excludes gitlinks and sparse-skipped paths that need no content. Files proven up to date by index stat data require no blob download. Repeating a reset after materialization uses the local objects and makes no data fetch.
CloneOptions::promisor_fetcher carries the fetcher through to the opened repository so blobless clone checkout can prefetch without a separate reopen.
On the serving side, pass the client's ObjectFilter to UploadPackStream::with_filter (or build it in memory with UploadPackStream::build). The filtered pack streams like an unfiltered one and holds the objects git pack-objects --filter selects: wanted objects and tag targets always, then the commits, trees and blobs the filter keeps.
Large-object promisors
A server can point clients at the remotes that hold some of its objects, such as a large-object promisor (LOP) with the big blobs, through the protocol v2 promisor-remote capability. PromisorAdvertisement models it: from_server_config builds it from promisor.advertise and promisor.sendFields, and UploadPack advertises it and collects the names a client accepts in ServeOptions::accepted_promisor_remotes. uploadpack.allowAnySHA1InWant lets a LOP served by grit hand out blobs no ref points at.
On the client, a v2 fetch reads the advertisement and runs PromisorHandshake::evaluate (PromisorHandshakeOptions says whether the fetch is partial and whether to pick the filter automatically): PromisorAcceptPolicy (promisor.acceptFromServer, checkFields, storeFields) decides, against the promisor remotes already in config (configured_promisor_remotes), which advertised remotes to accept, and each verdict is a PromisorRejection or acceptance. Only a partial fetch accepts anything: one with a filter, or one from a remote configured as a promisor remote. The accepted names go back to the server with both the ls-refs and the fetch request, so a stateless smart-HTTP server sees them where it builds the pack. With FetchOptions::auto_filter the filter comes from the accepted remotes (PromisorDecision::combined_filter). The result is in FetchOutcome::promisor and CloneOutcome::promisor.
use grit_lib::remote::clone::{clone, CloneOptions};
let opts = CloneOptions::new("https://git.example.com/project.git", "project".into())
.with_auto_filter(true)
.with_config(vec![
("remote.lop.url".into(), "https://lop.example.com/project.git".into()),
("remote.lop.promisor".into(), "true".into()),
("promisor.acceptFromServer".into(), "knownUrl".into()),
]);
let outcome = clone(opts, &mut progress, &cancel, None)?;
for remote in outcome.promisor.iter().flat_map(|h| h.decision.accepted()) {
println!("accepted {}", remote.name);
}
Accepting never creates a remote, and lazy fetches use the URL configured locally, not the advertised one.
Serving a repository whose large blobs live on a LOP
After repo.maintenance().offload_blobs (see Maintenance), a server's large blobs live only on its LOP, and the rest of the repository sits in a .promisor pack. UploadPack serves such a repository by Git's rule. A client that accepted an advertised promisor remote gets packs without the promised blobs it lacks, and fetches those from the LOP. For any other client, the server either fetches them first or refuses with ServeError::ObjectMissing. That error carries a structured reason and reaches the client as an ERR line before any pack data. Fetching first needs ServeOptions::lazy_fetch, or uploadpack.lazyFetch when it is None, plus a PromisorFetcher on the served repository. The library reads no environment: ServeOptions::lazy_fetch_from_environment maps GIT_NO_LAZY_FETCH, and ServeOptions::attach_promisor_fetcher gives the opened repository a fetcher only when ServeOptions::lazy_fetch_enabled, and takes away any it was opened with otherwise, so a server without lazy fetch never fetches. Each fetch is planned again after a lazy fetch, so the client's filter still applies to the fetched blobs. ReceivePack into such a repository accepts pushed trees that name promised blobs, as Git's connectivity check does. Repositories without promisor remotes keep the bitmap and pack-reuse fast path. Only these partial repositories plan their packs with the object walk, checking each blob is stored.
A local clone or fetch from a repository with promisor remotes of its own goes through the same in-process upload-pack instead of copying its object store, which would come up short.
Bundles
Offline bundle files are documented on the Bundle guide (Bundles). Smart HTTP and local remotes above cover online fetch/push.