radicle 0.25.1

Radicle standard library
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
use std::collections::HashMap;
use std::path::{Path, PathBuf};

use radicle_core::{NodeId, RepoId};
use radicle_git_metadata::author::{Author, Time};
use radicle_git_metadata::commit::CommitData;
use radicle_git_metadata::commit::headers::Headers;
use radicle_git_metadata::commit::trailers::OwnedTrailer;
use radicle_oid::Oid;

use crate::git;
use crate::identity::doc;
use crate::storage::HasRepoId;
use crate::storage::refs::sigrefs::git::{object, reference};
use crate::storage::refs::{REFS_BLOB_PATH, Refs, SIGNATURE_BLOB_PATH, SIGREFS_BRANCH};

const MOCKED_IDENTITY: u8 = 99u8;

enum WriteTreeBehavior {
    /// [`object::Writer::write_tree`] returns `Ok(oid)`.
    Ok(Oid),
    /// [`object::Writer::write_tree`] returns `Err(…)`.
    Error,
}

/// [`object::Writer::write_commit`] returns `Ok(oid)`.
struct WriteCommitBehavior(Oid);

enum WriteReferenceBehavior {
    /// [`reference::Writer::write_reference`] returns `Ok(())`.
    Ok,
    /// [`reference::Writer::write_reference`] returns `Err(…)`.
    Error,
}

enum BlobBehavior {
    /// [`object::Reader::read_blob`] returns `Ok(Some(blob))`.
    Present(Vec<u8>),
    /// [`object::Reader::read_blob`] returns `Ok(None)`.
    Missing,
    /// [`object::Reader::read_blob`] returns `Err(…)`.
    Error,
}

enum RefBehavior {
    /// [`reference::Reader::find_reference`] returns `Ok(Some(oid))`.
    Present(Oid),
    /// [`reference::Reader::find_reference`] returns `Ok(None)`.
    Missing,
    /// [`reference::Reader::find_reference`] returns `Err(…)`.
    Error,
}

pub struct MockRepository {
    commits: HashMap<Oid, CommitBehavior>,
    blobs: HashMap<(Oid, PathBuf), BlobBehavior>,
    references: HashMap<String, RefBehavior>,
    write_tree: Option<WriteTreeBehavior>,
    write_commit: Option<WriteCommitBehavior>,
    write_reference: Option<WriteReferenceBehavior>,
}

enum CommitBehavior {
    /// [`object::Reader::read_commit`] returns `Ok(Some(bytes))`.
    Present(Box<CommitData<Oid, Oid>>),
}

impl MockRepository {
    pub fn new() -> MockRepository {
        MockRepository {
            commits: HashMap::new(),
            blobs: HashMap::new(),
            references: HashMap::new(),
            write_tree: None,
            write_commit: None,
            write_reference: None,
        }
        .with_identity(oid(MOCKED_IDENTITY))
    }

    pub fn with_commit(mut self, oid: Oid, data: CommitData<Oid, Oid>) -> Self {
        self.commits
            .insert(oid, CommitBehavior::Present(Box::new(data)));
        self
    }

    pub fn with_rad_sigrefs(mut self, namespace: &NodeId, commit: Oid) -> MockRepository {
        self.references
            .insert(sigrefs_ref_name(namespace), RefBehavior::Present(commit));
        self
    }

    pub fn with_missing_rad_sigrefs(mut self, namespace: &NodeId) -> MockRepository {
        self.references
            .insert(sigrefs_ref_name(namespace), RefBehavior::Missing);
        self
    }

    pub fn with_rad_sigrefs_error(mut self, namespace: &NodeId) -> MockRepository {
        self.references
            .insert(sigrefs_ref_name(namespace), RefBehavior::Error);
        self
    }

    pub fn with_refs(
        self,
        commit: Oid,
        refs: impl IntoIterator<Item = (git::fmt::RefString, Oid)>,
    ) -> MockRepository {
        let refs = Refs::from(refs.into_iter());
        self.with_blob(commit, Path::new(REFS_BLOB_PATH), refs.canonical())
    }

    pub fn with_refs_error(self, commit: Oid) -> MockRepository {
        self.with_blob_error(commit, Path::new(REFS_BLOB_PATH))
    }

    pub fn with_missing_refs(self, commit: Oid) -> MockRepository {
        self.with_missing_blob(commit, Path::new(REFS_BLOB_PATH))
    }

    pub fn with_invalid_refs(self, commit: Oid) -> MockRepository {
        self.with_blob(
            commit,
            Path::new(REFS_BLOB_PATH),
            b"NOT VALID REFS\n".to_vec(),
        )
    }

    pub fn with_signature(self, commit: Oid, sig_id: u8) -> MockRepository {
        self.with_blob(commit, Path::new(SIGNATURE_BLOB_PATH), vec![sig_id; 64])
    }

    pub fn with_valid_signature(self, commit: Oid, refs: &Refs) -> MockRepository {
        let signer = signing_key();
        let signature = crypto::signature::Signer::try_sign(&signer, &refs.canonical())
            .expect("mock signing key must sign refs");

        self.with_blob(commit, Path::new(SIGNATURE_BLOB_PATH), signature.to_vec())
    }

    pub fn with_signature_error(self, commit: Oid) -> MockRepository {
        self.with_blob_error(commit, Path::new(SIGNATURE_BLOB_PATH))
    }

    pub fn with_missing_signature(self, commit: Oid) -> MockRepository {
        self.with_missing_blob(commit, Path::new(SIGNATURE_BLOB_PATH))
    }

    pub fn with_invalid_signature(self, commit: Oid) -> MockRepository {
        let bytes = vec![0u8; 1];
        self.with_blob(commit, Path::new(SIGNATURE_BLOB_PATH), bytes)
    }

    pub fn with_identity(self, commit: Oid) -> Self {
        self.with_blob(commit, &identity_path(), vec![])
    }

    fn with_blob(mut self, commit: Oid, path: &Path, bytes: Vec<u8>) -> Self {
        self.blobs
            .insert((commit, path.to_path_buf()), BlobBehavior::Present(bytes));
        self
    }

    fn with_blob_error(mut self, commit: Oid, path: &Path) -> Self {
        self.blobs
            .insert((commit, path.to_path_buf()), BlobBehavior::Error);
        self
    }

    fn with_missing_blob(mut self, commit: Oid, path: &Path) -> Self {
        self.blobs
            .insert((commit, path.to_path_buf()), BlobBehavior::Missing);
        self
    }

    pub fn with_write_tree_error(mut self) -> Self {
        self.write_tree = Some(WriteTreeBehavior::Error);
        self
    }

    pub fn with_write_tree_ok(mut self, oid: Oid) -> Self {
        self.write_tree = Some(WriteTreeBehavior::Ok(oid));
        self
    }

    pub fn with_write_commit_ok(mut self, oid: Oid) -> Self {
        self.write_commit = Some(WriteCommitBehavior(oid));
        self
    }

    pub fn with_write_reference_ok(mut self) -> Self {
        self.write_reference = Some(WriteReferenceBehavior::Ok);
        self
    }

    pub fn with_write_reference_error(mut self) -> Self {
        self.write_reference = Some(WriteReferenceBehavior::Error);
        self
    }
}

impl HasRepoId for MockRepository {
    fn rid(&self) -> radicle_core::RepoId {
        rid()
    }
}

impl object::Reader for MockRepository {
    fn read_commit(&self, oid: &Oid) -> Result<Option<Vec<u8>>, object::error::ReadCommit> {
        match self.commits.get(oid) {
            Some(CommitBehavior::Present(data)) => Ok(Some(data.to_string().as_bytes().to_vec())),
            None => Ok(None),
        }
    }

    fn read_blob(
        &self,
        commit: &Oid,
        path: &Path,
    ) -> Result<Option<object::Blob>, object::error::ReadBlob> {
        let key = (*commit, path.to_path_buf());
        match self.blobs.get(&key) {
            Some(BlobBehavior::Present(bytes)) => Ok(Some(object::Blob {
                oid: *commit,
                bytes: bytes.clone(),
            })),
            Some(BlobBehavior::Missing) | None => Ok(None),
            Some(BlobBehavior::Error) => Err(object::error::ReadBlob::other(
                std::io::Error::other("mock blob error"),
            )),
        }
    }
}

impl reference::Reader for MockRepository {
    fn find_reference(
        &self,
        reference: &git::fmt::Namespaced,
    ) -> Result<Option<Oid>, reference::error::FindReference> {
        match self.references.get(reference.as_str()) {
            Some(RefBehavior::Present(oid)) => Ok(Some(*oid)),
            Some(RefBehavior::Missing) | None => Ok(None),
            Some(RefBehavior::Error) => Err(reference::error::FindReference::other(
                std::io::Error::other("mock reference error"),
            )),
        }
    }
}

impl object::Writer for MockRepository {
    fn write_tree(
        &self,
        _refs: object::RefsEntry,
        _signature: object::SignatureEntry,
    ) -> Result<Oid, object::error::WriteTree> {
        match &self.write_tree {
            Some(WriteTreeBehavior::Ok(oid)) => Ok(*oid),
            Some(WriteTreeBehavior::Error) | None => Err(object::error::WriteTree::write_error(
                std::io::Error::other("mock write_tree error"),
            )),
        }
    }

    fn write_commit(&self, _bytes: &[u8]) -> Result<Oid, object::error::WriteCommit> {
        match &self.write_commit {
            Some(WriteCommitBehavior(oid)) => Ok(*oid),
            None => Err(object::error::WriteCommit::other(std::io::Error::other(
                "mock write_commit error",
            ))),
        }
    }
}

impl reference::Writer for MockRepository {
    fn write_reference(
        &self,
        _reference: &git::fmt::Namespaced,
        _commit: Oid,
        _parent: Option<Oid>,
        _reflog: String,
    ) -> Result<(), reference::error::WriteReference> {
        match &self.write_reference {
            Some(WriteReferenceBehavior::Ok) => Ok(()),
            Some(WriteReferenceBehavior::Error) | None => {
                Err(reference::error::WriteReference::other(
                    std::io::Error::other("mock write_reference error"),
                ))
            }
        }
    }
}

fn signing_key() -> crypto::SigningKey {
    crypto::SigningKey::mock(1)
}

/// Always signs successfully, returning a fixed 64-byte signature.
#[derive(Clone)]
pub struct AlwaysSign(crypto::SigningKey);

impl AlwaysSign {
    const SIGNATURE: [u8; 64] = [1u8; 64];

    pub fn new() -> Self {
        AlwaysSign(signing_key())
    }

    pub fn signature() -> crypto::Signature {
        crypto::Signature::from(Self::SIGNATURE)
    }
}

impl crypto::signature::Signer<crypto::Signature> for AlwaysSign {
    fn try_sign(&self, _msg: &[u8]) -> Result<crypto::Signature, crypto::signature::Error> {
        Ok(Self::signature())
    }
}

impl crypto::signature::Verifier<crypto::Signature> for AlwaysSign {
    fn verify(
        &self,
        _msg: &[u8],
        _sig: &crypto::Signature,
    ) -> Result<(), crypto::signature::Error> {
        Ok(())
    }
}

impl crypto::signature::Keypair for AlwaysSign {
    type VerifyingKey = crypto::VerifyingKey;

    fn verifying_key(&self) -> Self::VerifyingKey {
        self.0.verifying_key()
    }
}

impl AsRef<crypto::PublicKey> for AlwaysSign {
    fn as_ref(&self) -> &crypto::PublicKey {
        self.0.as_ref()
    }
}

/// Always fails to sign.
pub struct NeverSign(crypto::SigningKey);

impl NeverSign {
    pub fn new() -> Self {
        NeverSign(signing_key())
    }
}

impl crypto::signature::Keypair for NeverSign {
    type VerifyingKey = crypto::VerifyingKey;

    fn verifying_key(&self) -> Self::VerifyingKey {
        self.0.verifying_key()
    }
}

impl crypto::signature::Signer<crypto::Signature> for NeverSign {
    fn try_sign(&self, _msg: &[u8]) -> Result<crypto::Signature, crypto::signature::Error> {
        Err(crypto::signature::Error::new())
    }
}

impl AsRef<crypto::PublicKey> for NeverSign {
    fn as_ref(&self) -> &crypto::PublicKey {
        self.0.as_ref()
    }
}

/// Construct an [`Oid`] from a single repeated byte.
///
/// `oid(1) != oid(2)` is guaranteed; use distinct values for distinct objects.
pub fn oid(n: u8) -> Oid {
    Oid::from_sha1([n; 20])
}

/// A fixed [`RepoId`] for tests.
pub fn rid() -> RepoId {
    RepoId::from(oid(MOCKED_IDENTITY))
}

/// A fixed [`NodeId`] for tests.
pub fn node_id() -> NodeId {
    NodeId::from([1u8; 32])
}

pub fn refs_heads_main() -> git::fmt::RefString {
    git::fmt::refname!("refs/heads/main")
}

/// A minimal [`radicle_git_metadata::author::Author`] for use in tests.
pub fn author() -> Author {
    Author {
        name: "test".to_owned(),
        email: "test@example.com".to_owned(),
        time: Time::new(0, 0),
    }
}

pub fn commit_data(parents: impl IntoIterator<Item = Oid>) -> CommitData<Oid, Oid> {
    let tree = oid(0);
    let author = author();
    let message = "test\n".to_owned();

    CommitData::new::<_, _, OwnedTrailer>(
        tree,
        parents,
        author.clone(),
        author,
        Headers::new(),
        message,
        vec![],
    )
}

fn sigrefs_ref_name(namespace: &NodeId) -> String {
    SIGREFS_BRANCH
        .with_namespace(git::fmt::Component::from(namespace))
        .as_str()
        .to_owned()
}

fn identity_path() -> PathBuf {
    Path::new("embeds").join(*doc::PATH)
}