sley-remote 0.0.1

Callable fetch, push, clone, and ls-remote orchestration over the sley transport and object stack.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
//! Callable SSH transport plumbing and fetch/push/ls-remote orchestration.
//!
//! These drive the transport-agnostic protocol codecs ([`sley_protocol`]) over an
//! `ssh` subprocess spawned via [`sley_transport::ssh_process_command`]. Like the
//! HTTP and local paths, everything is taken as explicit parameters — the
//! already-resolved [`RemoteUrl`], the [`ObjectFormat`], `git_dir`, the repository
//! [`GitConfig`], and the seam objects ([`CredentialProvider`], [`ProgressSink`]) —
//! so they never read process-global state, parse arguments, or print. SSH does not
//! authenticate at this layer (it delegates to the `ssh` program), so the
//! credential seam is accepted for uniformity but unused.
//!
//! The `ssh` program is chosen by [`ssh_program`], which reads the `GIT_SSH`
//! environment variable (git's standard mechanism) and falls back to `ssh`; this is
//! the one piece of ambient state the SSH transport inherently depends on.
//!
//! SSH mirrors the HTTP path ([`crate::http`]): two ref advertisements are read
//! from the spawned process's stdout (the second, re-advertised set in the RPC
//! stream is skipped), then the upload-pack/receive-pack request is written to its
//! stdin and the packfile/report read back from stdout. The ref-map / `FETCH_HEAD`
//! / prune helpers and the push-planning helpers are shared with the other
//! transports via [`crate::fetch`] and [`crate::push`].

use std::collections::HashMap;
use std::env;
use std::io::Read;
use std::path::Path;
use std::process::{Child, ChildStdin, ChildStdout, Command as ProcessCommand, Stdio};

use sley_core::{Capability, GitError, ObjectFormat, ObjectId, Result};
use sley_fetch::{install_upload_pack_raw_promisor_response, install_upload_pack_raw_response};
use sley_odb::{FileObjectDatabase, build_reachable_pack, collect_reachable_object_ids};
use sley_protocol::{
    GitService, ProtocolV2FetchShallowInfo, ReceivePackCommand, ReceivePackFeatures,
    ReceivePackPushRequestOptions, RefAdvertisement, UploadPackFeatures,
    UploadPackNegotiationRequest, UploadPackRawPackfileResponse, UploadPackRequest,
    build_receive_pack_push_request, parse_receive_pack_features, parse_refspec,
    parse_upload_pack_features, plan_push_commands, read_receive_pack_report_status,
    read_ref_advertisement_set, read_upload_pack_raw_packfile_response,
    read_upload_pack_shallow_info_and_raw_packfile_response, write_receive_pack_push_request,
    write_upload_pack_negotiation_request, write_upload_pack_request,
};
use sley_refs::FileRefStore;
use sley_transport::{RemoteTransport, RemoteUrl, SshCommandVariant, ssh_process_command};

use crate::{PushOutcome, PushRequest};

/// The `ssh` program to spawn for SSH transport: the `GIT_SSH` environment
/// variable when set, otherwise `ssh`. This mirrors git's basic `GIT_SSH`
/// selection (the richer `GIT_SSH_COMMAND`/`core.sshCommand` forms are not
/// handled, matching the CLI behavior being lifted).
pub fn ssh_program() -> String {
    env::var("GIT_SSH").unwrap_or_else(|_| "ssh".into())
}

/// Push to a resolved SSH `remote` from the repository at `git_dir`.
///
/// Performs the work the CLI's `push_ssh_repository` did, sharing the
/// push-planning helpers with the HTTP and local transports: advertises the
/// remote's refs over `ssh`, plans the receive-pack commands for `refspecs`,
/// rejects non-fast-forward updates (unless forced), builds the pack of objects
/// the remote lacks, sends the receive-pack request, and validates the
/// report-status. `credentials` is accepted for seam uniformity but unused. The
/// "To <remote>" summary and set-upstream config stay with the caller, driven from
/// [`PushOutcome::commands`].
pub(crate) struct SshPushRequest<'a> {
    pub git_dir: &'a Path,
    pub common_git_dir: &'a Path,
    pub format: ObjectFormat,
    pub remote: &'a RemoteUrl,
    pub refspecs: &'a [String],
    pub force: bool,
}

pub(crate) struct SshPushCommandsRequest<'a> {
    pub common_git_dir: &'a Path,
    pub format: ObjectFormat,
    pub remote: &'a RemoteUrl,
    pub command_forces: Vec<(ReceivePackCommand, bool)>,
    pub pack_objects: Vec<ObjectId>,
}

pub(crate) struct SshPushPlan {
    pub(crate) commands: Vec<ReceivePackCommand>,
    pub(crate) pack_objects: Vec<ObjectId>,
    child: Child,
    stdin: Option<ChildStdin>,
    stdout: ChildStdout,
    features: ReceivePackFeatures,
    advertisements: Vec<RefAdvertisement>,
    remote: RemoteUrl,
}

pub(crate) fn plan_push_ssh(request: SshPushRequest<'_>) -> Result<SshPushPlan> {
    let SshPushRequest {
        git_dir,
        common_git_dir,
        format,
        remote,
        refspecs,
        force,
    } = request;
    if remote.transport != RemoteTransport::Ssh {
        return Err(GitError::InvalidFormat(
            "SSH receive-pack requires an SSH remote".into(),
        ));
    }
    let ssh = ssh_process_command(
        remote,
        GitService::ReceivePack,
        ssh_program(),
        SshCommandVariant::OpenSsh,
    )?;
    let mut child = ProcessCommand::new(&ssh.program)
        .args(&ssh.args)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()?;
    let mut stdout = child
        .stdout
        .take()
        .ok_or_else(|| GitError::Command("ssh receive-pack stdout was not piped".into()))?;
    let stdin = child
        .stdin
        .take()
        .ok_or_else(|| GitError::Command("ssh receive-pack stdin was not piped".into()))?;

    let advertisement_set = read_ref_advertisement_set(format, &mut stdout)?;
    let features = advertisement_set
        .refs
        .first()
        .map(|advertisement| parse_receive_pack_features(&advertisement.capabilities))
        .transpose()?
        .unwrap_or_default();
    if let Some(remote_format) = features.object_format {
        if remote_format != format {
            return Err(GitError::InvalidObjectId(format!(
                "remote repository uses {}, local repository uses {}",
                remote_format.name(),
                format.name()
            )));
        }
    } else if format != ObjectFormat::Sha1 {
        return Err(GitError::InvalidObjectId(format!(
            "remote repository did not advertise object-format for {} push",
            format.name()
        )));
    }

    let local_store = FileRefStore::new(git_dir, format);
    let local_refs = crate::push::local_push_source_refs(&local_store, format)?;
    let parsed_refspecs = refspecs
        .iter()
        .map(|refspec| parse_refspec(&crate::push::normalize_push_refspec(refspec)))
        .collect::<Result<Vec<_>>>()?;
    let mut command_forces = Vec::new();
    for refspec in &parsed_refspecs {
        for command in plan_push_commands(
            format,
            &local_refs,
            &advertisement_set.refs,
            std::slice::from_ref(refspec),
        )? {
            command_forces.push((command, force || refspec.force));
        }
    }
    let commands = command_forces
        .iter()
        .map(|(command, _)| command.clone())
        .collect::<Vec<_>>();
    if commands.is_empty() {
        drop(stdin);
        return Ok(SshPushPlan {
            commands,
            pack_objects: Vec::new(),
            child,
            stdin: None,
            stdout,
            features,
            advertisements: advertisement_set.refs,
            remote: remote.clone(),
        });
    }

    let local_db = FileObjectDatabase::from_git_dir(common_git_dir, format);
    crate::push::reject_non_fast_forward_pushes(&local_db, format, &command_forces)?;
    Ok(SshPushPlan {
        commands,
        pack_objects: Vec::new(),
        child,
        stdin: Some(stdin),
        stdout,
        features,
        advertisements: advertisement_set.refs,
        remote: remote.clone(),
    })
}

pub(crate) fn plan_push_ssh_commands(request: SshPushCommandsRequest<'_>) -> Result<SshPushPlan> {
    let SshPushCommandsRequest {
        common_git_dir,
        format,
        remote,
        command_forces,
        pack_objects,
    } = request;
    if remote.transport != RemoteTransport::Ssh {
        return Err(GitError::InvalidFormat(
            "SSH receive-pack requires an SSH remote".into(),
        ));
    }
    let ssh = ssh_process_command(
        remote,
        GitService::ReceivePack,
        ssh_program(),
        SshCommandVariant::OpenSsh,
    )?;
    let mut child = ProcessCommand::new(&ssh.program)
        .args(&ssh.args)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()?;
    let mut stdout = child
        .stdout
        .take()
        .ok_or_else(|| GitError::Command("ssh receive-pack stdout was not piped".into()))?;
    let stdin = child
        .stdin
        .take()
        .ok_or_else(|| GitError::Command("ssh receive-pack stdin was not piped".into()))?;

    let advertisement_set = read_ref_advertisement_set(format, &mut stdout)?;
    let features = advertisement_set
        .refs
        .first()
        .map(|advertisement| parse_receive_pack_features(&advertisement.capabilities))
        .transpose()?
        .unwrap_or_default();
    if let Some(remote_format) = features.object_format {
        if remote_format != format {
            return Err(GitError::InvalidObjectId(format!(
                "remote repository uses {}, local repository uses {}",
                remote_format.name(),
                format.name()
            )));
        }
    } else if format != ObjectFormat::Sha1 {
        return Err(GitError::InvalidObjectId(format!(
            "remote repository did not advertise object-format for {} push",
            format.name()
        )));
    }

    let commands = command_forces
        .iter()
        .map(|(command, _)| command.clone())
        .collect::<Vec<_>>();

    if commands.is_empty() {
        drop(stdin);
        return Ok(SshPushPlan {
            commands,
            pack_objects,
            child,
            stdin: None,
            stdout,
            features,
            advertisements: advertisement_set.refs,
            remote: remote.clone(),
        });
    }

    let local_db = FileObjectDatabase::from_git_dir(common_git_dir, format);
    crate::push::reject_non_fast_forward_pushes(&local_db, format, &command_forces)?;
    Ok(SshPushPlan {
        commands,
        pack_objects,
        child,
        stdin: Some(stdin),
        stdout,
        features,
        advertisements: advertisement_set.refs,
        remote: remote.clone(),
    })
}

pub(crate) fn execute_push_ssh_plan(
    request: PushRequest<'_>,
    mut plan: SshPushPlan,
) -> Result<PushOutcome> {
    if plan.commands.is_empty() {
        return Ok(PushOutcome::default());
    }
    let mut stdin = plan
        .stdin
        .take()
        .ok_or_else(|| GitError::Command("ssh receive-pack stdin was not available".into()))?;
    let commands = plan.commands.clone();
    let local_db = FileObjectDatabase::from_git_dir(request.common_git_dir, request.format);
    let remote_excluded_tips =
        crate::remote_advertisement_tips_known_to_local(&local_db, &plan.advertisements)?;
    let remote_excluded =
        collect_reachable_object_ids(&local_db, request.format, remote_excluded_tips)?;
    let starts = crate::pack::push_pack_roots(&commands, &plan.pack_objects);
    let packfile = build_reachable_pack(&local_db, request.format, starts, &remote_excluded)?
        .map(|pack| pack.pack)
        .unwrap_or_default();
    let request = build_receive_pack_push_request(
        &plan.features,
        commands.clone(),
        packfile,
        ReceivePackPushRequestOptions {
            report_status: plan.features.report_status,
            ofs_delta: plan.features.ofs_delta,
            quiet: request.options.quiet && plan.features.quiet,
            object_format: plan
                .features
                .object_format
                .filter(|_| request.format != ObjectFormat::Sha1),
            ..ReceivePackPushRequestOptions::default()
        },
    )?;
    write_receive_pack_push_request(&mut stdin, &request)?;
    drop(stdin);

    let report = if plan.features.report_status {
        let report = read_receive_pack_report_status(&mut plan.stdout)?;
        crate::push::validate_receive_pack_report(&report)?;
        Some(report)
    } else {
        let mut sink = Vec::new();
        plan.stdout.read_to_end(&mut sink)?;
        None
    };
    let output = plan.child.wait_with_output()?;
    if !output.status.success() {
        return Err(GitError::Command(format!(
            "ssh receive-pack failed for {}: {}",
            ssh_remote_display(&plan.remote),
            String::from_utf8_lossy(&output.stderr).trim()
        )));
    }

    Ok(PushOutcome { commands, report })
}

/// List the advertised refs for a resolved SSH `remote`, mirroring the records the
/// HTTP/local paths return ([`crate::ls_remote::LsRemoteRecord`]): advertise over
/// `ssh`, then apply the `--heads`/`--tags`/`--refs` class filters and the
/// caller-supplied `matches` predicate. Returns the records and the object format
/// in effect (currently SHA-1 only).
pub(crate) fn ls_remote_ssh(
    remote: &RemoteUrl,
    filter: &crate::ls_remote::LsRemoteFilter,
    matches: &dyn Fn(&str) -> bool,
) -> Result<(Vec<crate::ls_remote::LsRemoteRecord>, ObjectFormat)> {
    if remote.transport != RemoteTransport::Ssh {
        return Err(GitError::InvalidFormat(
            "SSH upload-pack requires an SSH remote".into(),
        ));
    }
    let ssh = ssh_process_command(
        remote,
        GitService::UploadPack,
        ssh_program(),
        SshCommandVariant::OpenSsh,
    )?;
    let output = ProcessCommand::new(&ssh.program)
        .args(&ssh.args)
        .stdin(Stdio::null())
        .output()?;
    let mut stdout = output.stdout.as_slice();
    let set = match read_ref_advertisement_set(ObjectFormat::Sha1, &mut stdout) {
        Ok(set) => set,
        Err(_) if !output.status.success() => {
            return Err(GitError::Command(format!(
                "ssh upload-pack failed for {}: {}",
                ssh_remote_display(remote),
                String::from_utf8_lossy(&output.stderr).trim()
            )));
        }
        Err(err) => return Err(err),
    };
    let features = set
        .refs
        .first()
        .map(|advertisement| parse_upload_pack_features(&advertisement.capabilities))
        .transpose()?
        .unwrap_or_default();
    let format = features.object_format.unwrap_or(ObjectFormat::Sha1);
    if format != ObjectFormat::Sha1 {
        return Err(GitError::Unsupported(format!(
            "ssh ls-remote currently supports SHA-1 advertisements, got {}",
            format.name()
        )));
    }
    let symrefs = features
        .symrefs
        .iter()
        .filter_map(|symref| symref.split_once(':'))
        .map(|(name, target)| (name.to_string(), target.to_string()))
        .collect::<HashMap<_, _>>();
    let mut records = Vec::new();
    for advertisement in set.refs {
        if advertisement.oid.is_null() {
            continue;
        }
        if filter.refs_only && (advertisement.name == "HEAD" || advertisement.name.ends_with("^{}"))
        {
            continue;
        }
        let is_head = advertisement.name.starts_with("refs/heads/");
        let is_tag = advertisement.name.starts_with("refs/tags/");
        if (filter.heads || filter.tags) && !((filter.heads && is_head) || (filter.tags && is_tag))
        {
            continue;
        }
        if !matches(&advertisement.name) {
            continue;
        }
        records.push(crate::ls_remote::LsRemoteRecord {
            oid: advertisement.oid,
            symref: symrefs.get(&advertisement.name).cloned(),
            name: advertisement.name,
        });
    }
    Ok((records, format))
}

/// Fetch `wants` from an SSH upload-pack remote into the repository at `git_dir`,
/// installing the resulting pack. Objects already present locally are skipped (for
/// non-shallow fetches); `promisor` selects promisor-pack installation.
///
/// When `deepen` is set the fetch is shallow: the request replays `shallow` (the
/// client's current boundary from `$GIT_DIR/shallow`) and asks the server to
/// truncate history to `deepen` commits. The returned [`ProtocolV2FetchShallowInfo`]
/// entries are the server's shallow-info updates the caller must fold into
/// `$GIT_DIR/shallow` (see [`crate::apply_shallow_info`]); they are empty for a
/// non-deepen fetch.
pub struct SshFetchPackRequest<'a> {
    /// Local repository `$GIT_DIR`.
    pub git_dir: &'a Path,
    /// Local repository object format.
    pub format: ObjectFormat,
    /// Resolved SSH remote.
    pub remote: &'a RemoteUrl,
    /// Upload-pack features advertised by the remote.
    pub features: &'a UploadPackFeatures,
    /// Wanted object ids.
    pub wants: Vec<ObjectId>,
    /// Existing shallow boundary to replay.
    pub shallow: Vec<ObjectId>,
    /// Requested deepen depth, if this is a shallow fetch.
    pub deepen: Option<u32>,
    /// Whether to install the response as a promisor pack.
    pub promisor: bool,
}

pub fn install_fetch_pack_via_ssh_upload_pack(
    request: SshFetchPackRequest<'_>,
) -> Result<Vec<ProtocolV2FetchShallowInfo>> {
    if request.wants.is_empty() {
        return Ok(Vec::new());
    }
    let local_db = FileObjectDatabase::from_git_dir(request.git_dir, request.format);
    // A deepen request must always reach the server (the shallow boundary may move
    // even when every wanted object is already present), so only the plain fetch
    // takes the "everything is local already" shortcut.
    if request.deepen.is_none() && all_wants_present(&local_db, &request.wants)? {
        return Ok(Vec::new());
    }
    let upload_request = UploadPackRequest {
        wants: request.wants,
        capabilities: ssh_shallow_request_capabilities(request.deepen),
        shallow: request.shallow,
        deepen: request.deepen,
        ..UploadPackRequest::default()
    };
    let haves = crate::local::local_have_oids(request.git_dir, request.format)?;
    // Only a deepen request gets a leading shallow-info section in the response;
    // a plain fetch must use the non-shallow reader (the response starts straight
    // at the NAK/ACK), preserving the existing SSH wire handling exactly.
    let (shallow_info, response) = if request.deepen.is_some() {
        ssh_upload_pack_shallow_fetch_response(
            request.remote,
            request.format,
            request.features,
            upload_request,
            haves,
        )?
    } else {
        let response = ssh_upload_pack_fetch_response(
            request.remote,
            request.format,
            request.features,
            upload_request,
            haves,
        )?;
        (Vec::new(), response)
    };
    if request.promisor {
        install_upload_pack_raw_promisor_response(&response, &local_db)?;
    } else {
        install_upload_pack_raw_response(&response, &local_db)?;
    }
    Ok(shallow_info)
}

fn all_wants_present(db: &FileObjectDatabase, wants: &[ObjectId]) -> Result<bool> {
    for want in wants {
        if !db.contains(want)? {
            return Ok(false);
        }
    }
    Ok(true)
}

/// The want-line capabilities for an SSH fetch: the `shallow` capability when a
/// deepen is requested, otherwise none (preserving the existing plain-fetch wire
/// form exactly).
fn ssh_shallow_request_capabilities(deepen: Option<u32>) -> Vec<Capability> {
    if deepen.is_some() {
        vec![Capability {
            name: "shallow".into(),
            value: None,
        }]
    } else {
        Vec::new()
    }
}

/// The upload-pack ref advertisements and parsed features for SSH `remote`.
pub fn ssh_upload_pack_advertisements(
    remote: &RemoteUrl,
    format: ObjectFormat,
) -> Result<(Vec<RefAdvertisement>, UploadPackFeatures)> {
    if remote.transport != RemoteTransport::Ssh {
        return Err(GitError::InvalidFormat(
            "SSH upload-pack requires an SSH remote".into(),
        ));
    }
    let ssh = ssh_process_command(
        remote,
        GitService::UploadPack,
        ssh_program(),
        SshCommandVariant::OpenSsh,
    )?;
    let output = ProcessCommand::new(&ssh.program)
        .args(&ssh.args)
        .stdin(Stdio::null())
        .output()?;
    let mut stdout = output.stdout.as_slice();
    let set = match read_ref_advertisement_set(format, &mut stdout) {
        Ok(set) => set,
        Err(_) if !output.status.success() => {
            return Err(GitError::Command(format!(
                "ssh upload-pack failed for {}: {}",
                ssh_remote_display(remote),
                String::from_utf8_lossy(&output.stderr).trim()
            )));
        }
        Err(err) => return Err(err),
    };
    let features = set
        .refs
        .first()
        .map(|advertisement| parse_upload_pack_features(&advertisement.capabilities))
        .transpose()?
        .unwrap_or_default();
    Ok((set.refs, features))
}

/// Post an upload-pack `request` + `haves` over SSH and read back the raw packfile
/// response. The leading re-advertised ref set in the RPC stream is read and
/// discarded before the request is written. For a plain (non-deepen) request; see
/// [`ssh_upload_pack_shallow_fetch_response`] for the deepen case.
pub fn ssh_upload_pack_fetch_response(
    remote: &RemoteUrl,
    format: ObjectFormat,
    _features: &UploadPackFeatures,
    request: UploadPackRequest,
    haves: Vec<ObjectId>,
) -> Result<UploadPackRawPackfileResponse> {
    let (_shallow, response) =
        ssh_upload_pack_fetch_response_inner(remote, format, request, haves, false)?;
    Ok(response)
}

/// Post a deepen upload-pack `request` + `haves` over SSH and read back the
/// shallow-info section plus the raw packfile response. Use this when `request`
/// carries a `shallow`/`deepen`/`deepen-since`/`deepen-not` argument: the response
/// is then prefixed with a shallow-info section (possibly empty). The returned
/// [`ProtocolV2FetchShallowInfo`] entries are the server's shallow-info updates.
pub fn ssh_upload_pack_shallow_fetch_response(
    remote: &RemoteUrl,
    format: ObjectFormat,
    _features: &UploadPackFeatures,
    request: UploadPackRequest,
    haves: Vec<ObjectId>,
) -> Result<(
    Vec<ProtocolV2FetchShallowInfo>,
    UploadPackRawPackfileResponse,
)> {
    ssh_upload_pack_fetch_response_inner(remote, format, request, haves, true)
}

/// Drive the `ssh` upload-pack subprocess for `request` + `haves`, reading back the
/// raw packfile response. When `expect_shallow_info` is set (the request is a
/// deepen request) the response's leading shallow-info section is parsed and
/// returned; otherwise no shallow-info is expected and the returned vec is empty.
fn ssh_upload_pack_fetch_response_inner(
    remote: &RemoteUrl,
    format: ObjectFormat,
    request: UploadPackRequest,
    haves: Vec<ObjectId>,
    expect_shallow_info: bool,
) -> Result<(
    Vec<ProtocolV2FetchShallowInfo>,
    UploadPackRawPackfileResponse,
)> {
    if remote.transport != RemoteTransport::Ssh {
        return Err(GitError::InvalidFormat(
            "SSH upload-pack requires an SSH remote".into(),
        ));
    }
    let ssh = ssh_process_command(
        remote,
        GitService::UploadPack,
        ssh_program(),
        SshCommandVariant::OpenSsh,
    )?;
    let mut child = ProcessCommand::new(&ssh.program)
        .args(&ssh.args)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()?;
    let mut stdout = child
        .stdout
        .take()
        .ok_or_else(|| GitError::Command("ssh upload-pack stdout was not piped".into()))?;
    let mut stdin = child
        .stdin
        .take()
        .ok_or_else(|| GitError::Command("ssh upload-pack stdin was not piped".into()))?;

    read_ref_advertisement_set(format, &mut stdout)?;
    write_upload_pack_request(&mut stdin, Some(&request))?;
    write_upload_pack_negotiation_request(
        &mut stdin,
        &UploadPackNegotiationRequest { haves, done: true },
    )?;
    drop(stdin);

    let result = if expect_shallow_info {
        read_upload_pack_shallow_info_and_raw_packfile_response(format, &mut stdout)?
    } else {
        (
            Vec::new(),
            read_upload_pack_raw_packfile_response(format, &mut stdout)?,
        )
    };
    let output = child.wait_with_output()?;
    if !output.status.success() {
        return Err(GitError::Command(format!(
            "ssh upload-pack failed for {}: {}",
            ssh_remote_display(remote),
            String::from_utf8_lossy(&output.stderr).trim()
        )));
    }
    Ok(result)
}

/// A human-readable rendering of an SSH `remote` for error messages. The CLI built
/// these messages from the resolved URL string; the library only has the parsed
/// [`RemoteUrl`], so reconstruct the `user@host[:port]/path` (or `host:path` SCP)
/// form for the diagnostic text.
fn ssh_remote_display(remote: &RemoteUrl) -> String {
    let host = remote.host.as_deref().unwrap_or("");
    let mut out = String::new();
    if let Some(user) = &remote.user {
        out.push_str(user);
        out.push('@');
    }
    out.push_str(host);
    if let Some(port) = remote.port {
        out.push(':');
        out.push_str(&port.to_string());
    }
    if !remote.path.is_empty() {
        if !out.is_empty() {
            out.push(':');
        }
        out.push_str(&remote.path);
    }
    out
}