puregit 0.0.1

A pure-Rust implementation of git, in the spirit of libgit2, built on purecrypto. Object model, packfiles, refs, and the smart transport over HTTP and SSH — client and server.
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
//! Git wire protocol **version 2** (the command-oriented protocol).
//!
//! Where v0/v1 begins every connection with a full ref advertisement, v2 begins
//! with a *capability* advertisement and then runs discrete commands the client
//! names: `ls-refs` (enumerate refs) and `fetch` (negotiate and receive a pack).
//! This module implements both halves — the server framing a v2 client (real
//! `git` included) drives, and the client framing to drive a v2 server — as
//! sans-IO functions over decoded pkt-lines.
//!
//! A v2 request is a `command=<name>` pkt-line, then a delim-pkt (`0001`), then
//! argument pkt-lines, then a flush. Responses are pkt-line sections; the fetch
//! response's `packfile` section multiplexes the pack over sideband channel 1.

use alloc::string::{String, ToString};
use alloc::vec::Vec;

use crate::error::{Error, Result};
use crate::oid::{HashAlgo, ObjectId};

use super::pktline::{self, Packet};

/// The largest pack payload carried in one `side-band-64k` pkt-line (max line
/// length less the 4-byte length prefix and the 1-byte band marker).
const SIDEBAND_MAX_PAYLOAD: usize = pktline::MAX_PKTLINE_LEN - 4 - 1;

/// A ref as `ls-refs` advertises it: its `(name, id, symref-target, peeled)` —
/// where `symref-target` is the target of a symbolic ref (e.g. `HEAD`) and
/// `peeled` is the commit an annotated tag dereferences to, each present only
/// when applicable.
pub type LsRef = (String, ObjectId, Option<String>, Option<ObjectId>);

/// The agent string this implementation advertises.
const AGENT: &str = concat!("puregit/", env!("CARGO_PKG_VERSION"));

/// Builds the v2 capability advertisement — the response to `GET
/// info/refs?service=git-upload-pack` when the client sent `Git-Protocol:
/// version=2`, and the greeting on a stateful v2 connection.
///
/// It announces protocol version 2 and the commands/capabilities this server
/// supports: `ls-refs` and `fetch` (with `shallow` and `filter`), plus the agent
/// and object-format.
pub fn capability_advertisement(algo: HashAlgo) -> Result<Vec<u8>> {
    let mut out = Vec::new();
    out.extend_from_slice(&pktline::encode_data(b"version 2\n")?);
    out.extend_from_slice(&pktline::encode_data(
        alloc::format!("agent={AGENT}\n").as_bytes(),
    )?);
    out.extend_from_slice(&pktline::encode_data(b"ls-refs=unborn\n")?);
    out.extend_from_slice(&pktline::encode_data(
        b"fetch=shallow filter ref-in-want packfile-uris\n",
    )?);
    out.extend_from_slice(&pktline::encode_data(
        alloc::format!("object-format={}\n", algo.name()).as_bytes(),
    )?);
    out.extend_from_slice(&pktline::encode_control(&Packet::Flush));
    Ok(out)
}

/// A parsed v2 command request: the command name and its argument lines.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Command {
    /// The command name from the `command=<name>` line (e.g. `ls-refs`).
    pub name: String,
    /// The capability lines that preceded the delimiter (e.g. `object-format`,
    /// `agent`).
    pub capabilities: Vec<String>,
    /// The argument lines after the delimiter, trimmed of their trailing newline.
    pub args: Vec<String>,
}

impl Command {
    /// Parses a v2 request: `command=<name>` and capability lines, a delim-pkt,
    /// then argument lines, terminated by a flush.
    pub fn parse(packets: &[Packet]) -> Result<Self> {
        let mut name = None;
        let mut capabilities = Vec::new();
        let mut args = Vec::new();
        let mut after_delim = false;

        for packet in packets {
            match packet {
                Packet::Delim => after_delim = true,
                Packet::Flush => break,
                Packet::Data(d) => {
                    let line = trim_newline(d);
                    let text = String::from_utf8_lossy(line).to_string();
                    if after_delim {
                        args.push(text);
                    } else if let Some(cmd) = text.strip_prefix("command=") {
                        name = Some(cmd.to_string());
                    } else {
                        capabilities.push(text);
                    }
                }
                Packet::ResponseEnd => break,
            }
        }

        Ok(Command {
            name: name.ok_or_else(|| Error::Protocol("v2: request has no command".into()))?,
            capabilities,
            args,
        })
    }

    /// Whether an argument line equal to `arg` is present.
    pub fn has_arg(&self, arg: &str) -> bool {
        self.args.iter().any(|a| a == arg)
    }
}

/// Builds the `ls-refs` response: one `"<oid> <name>"` line per ref (with
/// `symref-target:` / `peeled:` attributes when requested), terminated by a
/// flush.
///
/// `refs` are `(name, id, symref_target, peeled)` tuples. `symref_target` is the
/// target a symbolic ref points at (only emitted when the client asked for
/// `symrefs`); `peeled` is the commit an annotated tag dereferences to (only
/// emitted when the client asked to `peel`). Only refs whose name starts with one
/// of the request's `ref-prefix` args are included (all, if none given).
pub fn encode_ls_refs_response(command: &Command, refs: &[LsRef]) -> Result<Vec<u8>> {
    let want_symrefs = command.has_arg("symrefs");
    let want_peel = command.has_arg("peel");
    let prefixes: Vec<&str> = command
        .args
        .iter()
        .filter_map(|a| a.strip_prefix("ref-prefix "))
        .collect();

    let mut out = Vec::new();
    for (name, id, symref, peeled) in refs {
        if !prefixes.is_empty() && !prefixes.iter().any(|p| name.starts_with(p)) {
            continue;
        }
        let mut line = alloc::format!("{} {name}", id.to_hex());
        if want_symrefs && let Some(target) = symref {
            line.push_str(&alloc::format!(" symref-target:{target}"));
        }
        if want_peel && let Some(p) = peeled {
            line.push_str(&alloc::format!(" peeled:{}", p.to_hex()));
        }
        line.push('\n');
        out.extend_from_slice(&pktline::encode_data(line.as_bytes())?);
    }
    out.extend_from_slice(&pktline::encode_control(&Packet::Flush));
    Ok(out)
}

/// The parsed arguments of a v2 `fetch` command.
#[derive(Debug, Clone, Default)]
pub struct FetchArgs {
    /// Object ids the client wants (`want <oid>` lines).
    pub wants: Vec<ObjectId>,
    /// Object ids the client already has (`have <oid>` lines).
    pub haves: Vec<ObjectId>,
    /// Whether the client sent `done` (negotiation is over; send the pack).
    pub done: bool,
    /// Whether the client offered `thin-pack`.
    pub thin_pack: bool,
    /// Whether the client asked for `no-progress`.
    pub no_progress: bool,
    /// A `deepen <n>` request (shallow fetch), if present.
    pub deepen: Option<u32>,
    /// The client's existing shallow boundary (`shallow <oid>` lines).
    pub shallows: Vec<ObjectId>,
    /// An object `filter` spec for a partial clone, if present.
    pub filter: Option<String>,
    /// Ref names the client wants by name (`want-ref <refname>`), the `ref-in-want`
    /// capability. The server resolves each to an id and echoes a `wanted-refs`
    /// section.
    pub want_refs: Vec<String>,
}

impl FetchArgs {
    /// Parses the argument lines of a `fetch` [`Command`].
    pub fn parse(algo: HashAlgo, command: &Command) -> Result<Self> {
        let mut args = FetchArgs::default();
        for line in &command.args {
            if let Some(oid) = line.strip_prefix("want ") {
                args.wants.push(ObjectId::from_hex(algo, oid.trim())?);
            } else if let Some(oid) = line.strip_prefix("have ") {
                args.haves.push(ObjectId::from_hex(algo, oid.trim())?);
            } else if let Some(oid) = line.strip_prefix("shallow ") {
                args.shallows.push(ObjectId::from_hex(algo, oid.trim())?);
            } else if let Some(depth) = line.strip_prefix("deepen ") {
                args.deepen = Some(
                    depth
                        .trim()
                        .parse()
                        .map_err(|_| Error::Protocol("v2 deepen: invalid depth".into()))?,
                );
            } else if let Some(spec) = line.strip_prefix("filter ") {
                args.filter = Some(spec.trim().to_string());
            } else if let Some(name) = line.strip_prefix("want-ref ") {
                args.want_refs.push(name.trim().to_string());
            } else if line == "done" {
                args.done = true;
            } else if line == "thin-pack" {
                args.thin_pack = true;
            } else if line == "no-progress" {
                args.no_progress = true;
            }
            // Unknown args (ofs-delta, include-tag, …) are accepted and ignored.
        }
        Ok(args)
    }
}

/// Wraps a built `pack` in the v2 `fetch` response: an `acknowledgments` section
/// is omitted (the client sent `done`), and the `packfile` section carries the
/// pack multiplexed over sideband channel 1, ended by a flush.
pub fn encode_fetch_response(pack: &[u8]) -> Result<Vec<u8>> {
    encode_fetch_response_with_shallow(&[], pack)
}

/// Like [`encode_fetch_response`], but precedes the `packfile` section with a
/// `shallow-info` section (`shallow <oid>` lines) when `shallow` is non-empty —
/// the v2 form of the shallow boundary announcement.
pub fn encode_fetch_response_with_shallow(shallow: &[ObjectId], pack: &[u8]) -> Result<Vec<u8>> {
    let mut out = Vec::new();
    if !shallow.is_empty() {
        out.extend_from_slice(&pktline::encode_data(b"shallow-info\n")?);
        for oid in shallow {
            out.extend_from_slice(&pktline::encode_data(
                alloc::format!("shallow {}\n", oid.to_hex()).as_bytes(),
            )?);
        }
        // A delim-pkt separates one section from the next.
        out.extend_from_slice(&pktline::encode_control(&Packet::Delim));
    }
    // The packfile section header, then sideband-framed pack data (band 1).
    out.extend_from_slice(&pktline::encode_data(b"packfile\n")?);
    for chunk in pack.chunks(SIDEBAND_MAX_PAYLOAD) {
        let mut line = Vec::with_capacity(chunk.len() + 1);
        line.push(1); // sideband channel 1: pack data
        line.extend_from_slice(chunk);
        out.extend_from_slice(&pktline::encode_data(&line)?);
    }
    out.extend_from_slice(&pktline::encode_control(&Packet::Flush));
    Ok(out)
}

// ---- client side ----------------------------------------------------------

/// Parses a v2 capability advertisement (the discovery response), returning the
/// advertised capability lines. Errors if the greeting is not `version 2` — the
/// caller then falls back to the v0/v1 advertisement.
pub fn parse_capability_advertisement(packets: &[Packet]) -> Result<Vec<String>> {
    let mut caps = Vec::new();
    let mut saw_version = false;
    for packet in packets {
        match packet {
            Packet::Data(d) => {
                let line = String::from_utf8_lossy(trim_newline(d)).to_string();
                if !saw_version {
                    if line != "version 2" {
                        return Err(Error::Protocol("v2: advertisement is not version 2".into()));
                    }
                    saw_version = true;
                } else {
                    caps.push(line);
                }
            }
            Packet::Flush => break,
            _ => {}
        }
    }
    if !saw_version {
        return Err(Error::Protocol("v2: empty advertisement".into()));
    }
    Ok(caps)
}

/// Encodes a v2 command request: the `command=<name>` line, capability lines, a
/// delim-pkt, the argument lines, and a flush.
pub fn encode_command(name: &str, capabilities: &[String], args: &[String]) -> Result<Vec<u8>> {
    let mut out = Vec::new();
    out.extend_from_slice(&pktline::encode_data(
        alloc::format!("command={name}\n").as_bytes(),
    )?);
    for cap in capabilities {
        out.extend_from_slice(&pktline::encode_data(alloc::format!("{cap}\n").as_bytes())?);
    }
    out.extend_from_slice(&pktline::encode_control(&Packet::Delim));
    for arg in args {
        out.extend_from_slice(&pktline::encode_data(alloc::format!("{arg}\n").as_bytes())?);
    }
    out.extend_from_slice(&pktline::encode_control(&Packet::Flush));
    Ok(out)
}

/// Parses an `ls-refs` response (`"<oid> <name>[ symref-target:…][ peeled:…]"`
/// lines, flush-terminated) into `(name, id)` advertised refs. The `symref-target`
/// and `peeled` attributes are ignored here (the caller only needs name→id).
pub fn parse_ls_refs_response(
    algo: HashAlgo,
    packets: &[Packet],
) -> Result<Vec<super::AdvertisedRef>> {
    let mut refs = Vec::new();
    for packet in packets {
        let line = match packet {
            Packet::Data(d) => trim_newline(d),
            Packet::Flush => break,
            _ => continue,
        };
        let text = core::str::from_utf8(line)
            .map_err(|_| Error::Protocol("v2 ls-refs: non-utf8 line".into()))?;
        let mut parts = text.split(' ');
        let (Some(oid), Some(name)) = (parts.next(), parts.next()) else {
            continue;
        };
        refs.push(super::AdvertisedRef {
            name: name.to_string(),
            id: ObjectId::from_hex(algo, oid)?,
        });
    }
    Ok(refs)
}

/// Demultiplexes the `packfile` section of a v2 `fetch` response into the raw
/// pack. Any preceding `acknowledgments`/`shallow-info` section is skipped; after
/// the `packfile` header, sideband channel-1 data is the pack, channel 2 is
/// progress (discarded), and channel 3 is a fatal error (surfaced).
pub fn parse_fetch_response(packets: &[Packet]) -> Result<Vec<u8>> {
    Ok(parse_fetch_response_full(HashAlgo::Sha1, packets)?.1)
}

/// Like [`parse_fetch_response`], but also returns the `shallow <oid>` boundary
/// from any `shallow-info` section (empty for a non-shallow fetch). `algo` parses
/// the shallow ids.
pub fn parse_fetch_response_full(
    algo: HashAlgo,
    packets: &[Packet],
) -> Result<(Vec<ObjectId>, Vec<u8>)> {
    let (shallow, _uris, pack) = parse_fetch_response_uris(algo, packets)?;
    Ok((shallow, pack))
}

/// Like [`parse_fetch_response_full`], but also returns the `packfile-uris`
/// section — the `(hash, uri)` pairs of packs the server offloaded for the
/// client to download and ingest alongside the inline pack. Empty when the
/// server sent everything inline.
#[allow(clippy::type_complexity)]
pub fn parse_fetch_response_uris(
    algo: HashAlgo,
    packets: &[Packet],
) -> Result<(Vec<ObjectId>, Vec<(String, String)>, Vec<u8>)> {
    let mut in_packfile = false;
    let mut in_uris = false;
    let mut shallow = Vec::new();
    let mut uris: Vec<(String, String)> = Vec::new();
    let mut pack = Vec::new();
    for packet in packets {
        let data = match packet {
            // A delim (or flush) ends the current non-pack section.
            Packet::Delim => {
                in_uris = false;
                continue;
            }
            Packet::Data(d) => d,
            _ => continue,
        };
        if !in_packfile {
            let line = trim_newline(data);
            if line == b"packfile" {
                in_packfile = true;
            } else if line == b"packfile-uris" {
                in_uris = true;
            } else if in_uris {
                // A `<hash> <uri>` line: split on the first space.
                let text = core::str::from_utf8(line)
                    .map_err(|_| Error::Protocol("v2 packfile-uris: non-utf8".into()))?;
                if let Some((hash, uri)) = text.split_once(' ') {
                    uris.push((hash.trim().to_string(), uri.trim().to_string()));
                }
            } else if let Some(oid) = line.strip_prefix(b"shallow ") {
                let text = core::str::from_utf8(oid)
                    .map_err(|_| Error::Protocol("v2 shallow: non-utf8".into()))?;
                shallow.push(ObjectId::from_hex(algo, text.trim())?);
            }
            continue;
        }
        match data.first() {
            Some(1) => pack.extend_from_slice(&data[1..]),
            Some(2) => {} // progress
            Some(3) => {
                return Err(Error::Protocol(alloc::format!(
                    "v2 fetch error: {}",
                    String::from_utf8_lossy(&data[1..])
                )));
            }
            _ => {}
        }
    }
    if !in_packfile {
        return Err(Error::Protocol(
            "v2 fetch: response had no packfile section".into(),
        ));
    }
    Ok((shallow, uris, pack))
}

/// Encodes a full v2 `fetch` response from its sections.
///
/// When `acknowledgments` is `Some`, an `acknowledgments` section is emitted
/// (an `ACK <oid>` per common object, or `NAK`, then `ready` — puregit completes
/// negotiation in one round, so it is always ready). A `shallow-info` section
/// follows when there is any `shallow`/`unshallow` boundary. The `packfile`
/// section (sideband) always comes last. Sections are delim-separated; the
/// response ends with a flush.
pub fn encode_fetch_sections(
    acknowledgments: Option<&[ObjectId]>,
    shallow: &[ObjectId],
    unshallow: &[ObjectId],
    wanted_refs: &[(ObjectId, String)],
    packfile_uris: &[(String, String)],
    pack: &[u8],
) -> Result<Vec<u8>> {
    let mut out = Vec::new();
    if let Some(common) = acknowledgments {
        out.extend_from_slice(&pktline::encode_data(b"acknowledgments\n")?);
        if common.is_empty() {
            out.extend_from_slice(&pktline::encode_data(b"NAK\n")?);
        } else {
            for oid in common {
                out.extend_from_slice(&pktline::encode_data(
                    alloc::format!("ACK {}\n", oid.to_hex()).as_bytes(),
                )?);
            }
        }
        out.extend_from_slice(&pktline::encode_data(b"ready\n")?);
        out.extend_from_slice(&pktline::encode_control(&Packet::Delim));
    }
    if !shallow.is_empty() || !unshallow.is_empty() {
        out.extend_from_slice(&pktline::encode_data(b"shallow-info\n")?);
        for oid in shallow {
            out.extend_from_slice(&pktline::encode_data(
                alloc::format!("shallow {}\n", oid.to_hex()).as_bytes(),
            )?);
        }
        for oid in unshallow {
            out.extend_from_slice(&pktline::encode_data(
                alloc::format!("unshallow {}\n", oid.to_hex()).as_bytes(),
            )?);
        }
        out.extend_from_slice(&pktline::encode_control(&Packet::Delim));
    }
    if !wanted_refs.is_empty() {
        // The `wanted-refs` section resolves each `want-ref` to `<oid> <name>`.
        out.extend_from_slice(&pktline::encode_data(b"wanted-refs\n")?);
        for (oid, name) in wanted_refs {
            out.extend_from_slice(&pktline::encode_data(
                alloc::format!("{} {name}\n", oid.to_hex()).as_bytes(),
            )?);
        }
        out.extend_from_slice(&pktline::encode_control(&Packet::Delim));
    }
    if !packfile_uris.is_empty() {
        // The `packfile-uris` section offloads some packs to URLs the client
        // downloads itself: one `<hash> <uri>` line each (the hash names the
        // downloaded pack so the client can verify it).
        out.extend_from_slice(&pktline::encode_data(b"packfile-uris\n")?);
        for (hash, uri) in packfile_uris {
            out.extend_from_slice(&pktline::encode_data(
                alloc::format!("{hash} {uri}\n").as_bytes(),
            )?);
        }
        out.extend_from_slice(&pktline::encode_control(&Packet::Delim));
    }
    out.extend_from_slice(&pktline::encode_data(b"packfile\n")?);
    for chunk in pack.chunks(SIDEBAND_MAX_PAYLOAD) {
        let mut line = Vec::with_capacity(chunk.len() + 1);
        line.push(1);
        line.extend_from_slice(chunk);
        out.extend_from_slice(&pktline::encode_data(&line)?);
    }
    out.extend_from_slice(&pktline::encode_control(&Packet::Flush));
    Ok(out)
}

/// Strips a single trailing `\n` from a line, if present.
fn trim_newline(line: &[u8]) -> &[u8] {
    match line.strip_suffix(b"\n") {
        Some(rest) => rest,
        None => line,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn capability_advertisement_announces_v2_and_commands() {
        let bytes = capability_advertisement(HashAlgo::Sha1).unwrap();
        let packets = pktline::decode_all(&bytes).unwrap();
        let lines: Vec<String> = packets
            .iter()
            .filter_map(|p| match p {
                Packet::Data(d) => Some(String::from_utf8_lossy(trim_newline(d)).to_string()),
                _ => None,
            })
            .collect();
        assert_eq!(lines[0], "version 2");
        assert!(lines.iter().any(|l| l == "ls-refs=unborn"));
        assert!(
            lines
                .iter()
                .any(|l| l == "fetch=shallow filter ref-in-want packfile-uris")
        );
        assert!(lines.iter().any(|l| l == "object-format=sha1"));
    }

    #[test]
    fn parses_a_command_with_caps_and_args() {
        let mut req = Vec::new();
        req.extend(pktline::encode_data(b"command=fetch\n").unwrap());
        req.extend(pktline::encode_data(b"object-format=sha1\n").unwrap());
        req.extend(pktline::encode_control(&Packet::Delim));
        req.extend(
            pktline::encode_data(b"want 1111111111111111111111111111111111111111\n").unwrap(),
        );
        req.extend(pktline::encode_data(b"done\n").unwrap());
        req.extend(pktline::encode_control(&Packet::Flush));

        let cmd = Command::parse(&pktline::decode_all(&req).unwrap()).unwrap();
        assert_eq!(cmd.name, "fetch");
        assert!(cmd.capabilities.iter().any(|c| c == "object-format=sha1"));
        assert!(cmd.has_arg("done"));

        let args = FetchArgs::parse(HashAlgo::Sha1, &cmd).unwrap();
        assert_eq!(args.wants.len(), 1);
        assert!(args.done);
    }

    #[test]
    fn ls_refs_filters_by_prefix_and_adds_attrs() {
        let mut req = Vec::new();
        req.extend(pktline::encode_data(b"command=ls-refs\n").unwrap());
        req.extend(pktline::encode_control(&Packet::Delim));
        req.extend(pktline::encode_data(b"symrefs\n").unwrap());
        req.extend(pktline::encode_data(b"ref-prefix refs/heads/\n").unwrap());
        req.extend(pktline::encode_control(&Packet::Flush));
        let cmd = Command::parse(&pktline::decode_all(&req).unwrap()).unwrap();

        let id = ObjectId::from_hex(HashAlgo::Sha1, &"a".repeat(40)).unwrap();
        let refs = alloc::vec![
            (
                "HEAD".to_string(),
                id,
                Some("refs/heads/main".to_string()),
                None
            ),
            ("refs/heads/main".to_string(), id, None, None),
            ("refs/tags/v1".to_string(), id, None, None),
        ];
        let resp = encode_ls_refs_response(&cmd, &refs).unwrap();
        let text = String::from_utf8_lossy(&resp);
        // HEAD is filtered out (doesn't match refs/heads/ prefix); main is kept;
        // the tag is filtered out.
        assert!(text.contains("refs/heads/main"));
        assert!(!text.contains("refs/tags/v1"));
        assert!(!text.contains("HEAD"));
    }

    #[test]
    fn client_parses_server_capability_advertisement() {
        let bytes = capability_advertisement(HashAlgo::Sha1).unwrap();
        let caps = parse_capability_advertisement(&pktline::decode_all(&bytes).unwrap()).unwrap();
        assert!(caps.iter().any(|c| c == "ls-refs=unborn"));
        assert!(
            caps.iter()
                .any(|c| c == "fetch=shallow filter ref-in-want packfile-uris")
        );
        // A v0/v1 advertisement (no `version 2`) is rejected so the caller falls
        // back.
        let v1 = pktline::encode_data(b"deadbeef refs/heads/main\n").unwrap();
        assert!(parse_capability_advertisement(&pktline::decode_all(&v1).unwrap()).is_err());
    }

    #[test]
    fn ls_refs_encode_then_parse_round_trips() {
        // Client encodes an ls-refs command; server parses it and answers; client
        // parses the answer back into refs.
        let caps = alloc::vec!["object-format=sha1".to_string()];
        let args = alloc::vec!["symrefs".to_string(), "ref-prefix refs/".to_string()];
        let request = encode_command("ls-refs", &caps, &args).unwrap();
        let cmd = Command::parse(&pktline::decode_all(&request).unwrap()).unwrap();
        assert_eq!(cmd.name, "ls-refs");

        let id = ObjectId::from_hex(HashAlgo::Sha1, &"b".repeat(40)).unwrap();
        let refs = alloc::vec![
            ("refs/heads/main".to_string(), id, None, None),
            ("refs/tags/v1".to_string(), id, None, None),
        ];
        let response = encode_ls_refs_response(&cmd, &refs).unwrap();
        let parsed =
            parse_ls_refs_response(HashAlgo::Sha1, &pktline::decode_all(&response).unwrap())
                .unwrap();
        assert_eq!(parsed.len(), 2);
        assert_eq!(parsed[0].name, "refs/heads/main");
        assert_eq!(parsed[0].id, id);
    }

    #[test]
    fn client_demuxes_the_fetch_packfile_section() {
        let response = encode_fetch_response(b"PACKcontents").unwrap();
        let pack = parse_fetch_response(&pktline::decode_all(&response).unwrap()).unwrap();
        assert_eq!(pack, b"PACKcontents");

        // A response with no packfile section is an error.
        let empty = pktline::encode_control(&Packet::Flush);
        assert!(parse_fetch_response(&pktline::decode_all(&empty).unwrap()).is_err());
    }

    #[test]
    fn packfile_uris_section_round_trips() {
        let uris = alloc::vec![
            (
                "aaaa".to_string(),
                "https://cdn.example/pack-aaaa.pack".to_string()
            ),
            (
                "bbbb".to_string(),
                "https://cdn.example/pack-bbbb.pack".to_string()
            ),
        ];
        let resp = encode_fetch_sections(None, &[], &[], &[], &uris, b"PACKmain").unwrap();
        let (_shallow, parsed_uris, pack) =
            parse_fetch_response_uris(HashAlgo::Sha1, &pktline::decode_all(&resp).unwrap())
                .unwrap();
        assert_eq!(pack, b"PACKmain");
        assert_eq!(parsed_uris, uris);

        // With no offloaded packs the section is absent and the list is empty.
        let plain = encode_fetch_sections(None, &[], &[], &[], &[], b"PACKx").unwrap();
        let (_s, no_uris, _p) =
            parse_fetch_response_uris(HashAlgo::Sha1, &pktline::decode_all(&plain).unwrap())
                .unwrap();
        assert!(no_uris.is_empty());
    }

    #[test]
    fn fetch_response_wraps_pack_in_sideband() {
        let resp = encode_fetch_response(b"PACKDATA").unwrap();
        let packets = pktline::decode_all(&resp).unwrap();
        // First a "packfile" header line, then a band-1 data line carrying it.
        assert_eq!(packets[0], Packet::Data(b"packfile\n".to_vec()));
        match &packets[1] {
            Packet::Data(d) => {
                assert_eq!(d[0], 1);
                assert_eq!(&d[1..], b"PACKDATA");
            }
            other => panic!("expected sideband data, got {other:?}"),
        }
        assert_eq!(packets.last(), Some(&Packet::Flush));
    }
}