diff --git a/.codespellrc b/.codespellrc index 11bb829ed..a20229636 100644 --- a/.codespellrc +++ b/.codespellrc @@ -1,5 +1,5 @@ # See: https://github.com/codespell-project/codespell#using-a-config-file [codespell] -skip = .git*,*.lock,.codespellrc,target,.jj,.direnv,simulation/modules/radicle-node/cue.mod/* +skip = .git*,*.lock,.codespellrc,target,.jj,.direnv,simulation/modules/radicle-node/cue.mod/*,crates/radicle-surf/src/test/platinum/* check-hidden = true ignore-words-list = ser,set,noes diff --git a/.typos.toml b/.typos.toml index 060f83629..1be401dcf 100644 --- a/.typos.toml +++ b/.typos.toml @@ -34,6 +34,7 @@ extend-ignore-re = [ [files] extend-exclude = [ + "crates/radicle-surf/src/test/platinum", "simulation/modules/radicle-node/cue.mod" ] diff --git a/Cargo.lock b/Cargo.lock index bd7cc8809..122824204 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1818,6 +1818,12 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hex-literal" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e712f64ec3850b98572bffac52e2c6f282b29fe6c5fa6d42334b30be438d95c1" + [[package]] name = "hmac" version = "0.12.1" @@ -2296,6 +2302,12 @@ dependencies = [ "autocfg", ] +[[package]] +name = "minicbor" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "124d887cb82f0b1469bdac3d1b65764a381eed1a54fdab0070e5772b13114521" + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -2927,7 +2939,7 @@ dependencies = [ "radicle-localtime", "radicle-log", "radicle-node", - "radicle-surf", + "radicle-surf 0.28.0 (registry+https://github.com/rust-lang/crates.io-index)", "radicle-term", "schemars", "serde", @@ -3073,6 +3085,7 @@ dependencies = [ name = "radicle-git-metadata" version = "0.2.0" dependencies = [ + "git2", "thiserror 2.0.18", ] @@ -3211,6 +3224,28 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fb935931bdd2a2966f3b584f3031d9d54ec0713ddbc563a0193d54e62a88ec73" +[[package]] +name = "radicle-surf" +version = "0.28.0" +dependencies = [ + "base64 0.21.7", + "flate2", + "git2", + "hex-literal", + "log", + "minicbor", + "nonempty 0.9.0", + "proptest", + "radicle-git-metadata", + "radicle-git-ref-format", + "radicle-oid", + "serde", + "serde_json", + "tempfile", + "thiserror 1.0.69", + "url", +] + [[package]] name = "radicle-surf" version = "0.28.0" @@ -4637,6 +4672,7 @@ dependencies = [ "idna", "percent-encoding", "serde", + "serde_derive", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index ff5b6c0fc..3c25da833 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,8 +2,6 @@ members = ["crates/*"] resolver = "2" -exclude = ["crates/radicle-surf"] # TODO: Remove exclusion. - [workspace.package] edition = "2024" license = "MIT OR Apache-2.0" diff --git a/crates/radicle-git-metadata/Cargo.toml b/crates/radicle-git-metadata/Cargo.toml index 05e237915..92578e314 100644 --- a/crates/radicle-git-metadata/Cargo.toml +++ b/crates/radicle-git-metadata/Cargo.toml @@ -11,4 +11,5 @@ repository.workspace = true rust-version.workspace = true [dependencies] -thiserror = { workspace = true, default-features = true } \ No newline at end of file +thiserror = { workspace = true, default-features = true } +git2 = { workspace = true, optional = true } \ No newline at end of file diff --git a/crates/radicle-git-metadata/src/author.rs b/crates/radicle-git-metadata/src/author.rs index e0c133658..f172cb63a 100644 --- a/crates/radicle-git-metadata/src/author.rs +++ b/crates/radicle-git-metadata/src/author.rs @@ -123,3 +123,16 @@ impl FromStr for Author { }) } } + +#[cfg(feature = "git2")] +impl TryFrom<&Author> for git2::Signature<'_> { + type Error = git2::Error; + + fn try_from(author: &Author) -> Result { + git2::Signature::new( + &author.name, + &author.email, + &git2::Time::new(author.time.seconds(), author.time.offset()), + ) + } +} diff --git a/crates/radicle-surf/CHANGELOG.md b/crates/radicle-surf/CHANGELOG.md index 7399d3b7d..666e1637a 100644 --- a/crates/radicle-surf/CHANGELOG.md +++ b/crates/radicle-surf/CHANGELOG.md @@ -27,7 +27,7 @@ changes include: - `Browser` is removed. Its methods are implemented directly with `Repository`. - Git will be the only supported VCS. Any extension points for other VCSes were removed. -- `Ref` and `RefScope` are removed. Re-use the `git-ref-format` crate and a new +- `Ref` and `RefScope` are removed. Reuse the `git-ref-format` crate and a new `Glob` type for the refspec patterns. - Added support of `Tree` and `Blob` that correspond to their definitions in Git. diff --git a/crates/radicle-surf/Cargo.toml b/crates/radicle-surf/Cargo.toml index d9029d0b6..94a112d17 100644 --- a/crates/radicle-surf/Cargo.toml +++ b/crates/radicle-surf/Cargo.toml @@ -1,59 +1,39 @@ [package] name = "radicle-surf" -description = "A code surfing library for Git repositories" -readme = "README.md" version = "0.28.0" -authors = ["The Radicle Team "] -homepage.workspace = true -repository.workspace = true +description = "A code surfing library for Git repositories" + +readme = "README.md" + edition.workspace = true license.workspace = true +repository.workspace = true rust-version.workspace = true -include = [ - "**/*.rs", - "Cargo.toml", - "data/git-platinum.tgz", -] - -[lib] -test = false -doctest = false - [features] # NOTE: testing `test_submodule_failure` on GH actions # is painful since it uses this specific repo and expects # certain branches to be setup. So we use this feature flag # to ignore the test on CI. gh-actions = [] -minicbor = ["radicle-git-ext/minicbor"] -serde = ["dep:serde", "url/serde"] +serde = ["dep:serde", "radicle-git-ref-format/serde", "radicle-oid/serde", "url/serde"] [dependencies] base64 = "0.21" +git2 = { workspace = true, features = ["vendored-libgit2"] } log = "0.4" +minicbor = { version = "0.13", features = ["std"], optional = true } nonempty = "0.9" +radicle-git-metadata = { workspace = true, features = ["git2"] } +radicle-git-ref-format = { workspace = true, features = ["macro"] } +radicle-oid = { workspace = true, features = ["git2", "sha1"] } +serde = { workspace = true, optional = true, features = ["derive"] } thiserror = "1.0" url = "2.5.4" -[dependencies.git2] -workspace = true - -[dependencies.radicle-git-ext] -version = "0.13.0" -path = "../radicle-git-ext" -features = ["serde"] - -[dependencies.radicle-std-ext] -version = "0.2.0" -path = "../radicle-std-ext" - -[dependencies.serde] -version = "1" -features = ["serde_derive"] -optional = true - -[build-dependencies] -anyhow = "1.0" +[dev-dependencies] flate2 = "1.1" -tar = "0.4.45" +hex-literal = "1.1.0" +proptest = { workspace = true } +serde_json = { workspace = true } +tempfile = { workspace = true } \ No newline at end of file diff --git a/crates/radicle-surf/DEVELOPMENT.md b/crates/radicle-surf/DEVELOPMENT.md index a3df0fa74..6610737c9 100644 --- a/crates/radicle-surf/DEVELOPMENT.md +++ b/crates/radicle-surf/DEVELOPMENT.md @@ -5,7 +5,7 @@ Thanks for wanting to contribute to `radicle-surf`! ## Building & Testing 🏗️ -We try to make development as seemless as possible so we can get down to the real work. We supply +We try to make development as seamless as possible so we can get down to the real work. We supply the toolchain via the `rust-toolchain` file, and the formatting rules `.rustmt.toml` file. For the [Nix](https://nixos.org/) inclined there is a `default.nix` file to get all the necessary @@ -52,7 +52,7 @@ of development. If more tests are needed then we should add them under `mod tests` in the relevant module. We strive to find properties of our programs so that we can use tools like `proptest` to extensively prove our -programs are correct. As well as this, we add unit tests to esnure the examples in our heads are +programs are correct. As well as this, we add unit tests to ensure the examples in our heads are correct, and testing out the ergonomics of our API first-hand. ## CI files 🤖 diff --git a/crates/radicle-surf/README.md b/crates/radicle-surf/README.md index 405e75585..33de830ec 100644 --- a/crates/radicle-surf/README.md +++ b/crates/radicle-surf/README.md @@ -2,8 +2,6 @@ A code surfing library for Git repositories 🏄‍♀️🏄‍♂️ -Welcome to `radicle-surf`! - `radicle-surf` is a library to describe a Git repository as a file system. It aims to provide an easy-to-use API to browse a repository via the concept of files and directories for any given revision. It also allows the user to diff @@ -11,12 +9,3 @@ any two different revisions. One of the use cases would be to create a web GUI for interacting with a Git repository (thinking GitHub, GitLab or similar systems). - -## Contributing - -To get started on contributing you can check out our [developing guide](../DEVELOPMENT.md), and also -our [LICENSE](../LICENSE) file. - -## The Community - -Join our community disccussions at [radicle.community](https://radicle.community)! diff --git a/crates/radicle-surf/docs/denotational-design.md b/crates/radicle-surf/docs/denotational-design.md index 88a2c41e6..779c37133 100644 --- a/crates/radicle-surf/docs/denotational-design.md +++ b/crates/radicle-surf/docs/denotational-design.md @@ -11,7 +11,7 @@ and view their differences. The stream of consciousness that gave birth to this document started with thinking how the user would interact with the system, identifying the key components. This is captured in [User Flow](#user-flow). From there we found nouns that represent objects in our system and verbs that represent functions over those objects. This iteratively informed us as -to what other actions we would need to supply. We would occassionally look at [GitHub](todo) and [Pijul Nest](todo) for +to what other actions we would need to supply. We would occasionally look at [GitHub](todo) and [Pijul Nest](todo) for inspiration, since we would like to imitate the features that they supply, and we ultimately want use one or both of these for our backends. @@ -33,7 +33,7 @@ repl = do But then we thought about what happens when we are in `browse` but we would like to change the history and see that file or directory at a different snapshot. This was captured in the pseudo-code below: ```haskell - src_foo_bar <- find... + src_foo_bar <- find… history' <- historyOf src_foo_bar ``` @@ -54,7 +54,7 @@ type Label -- |-- bar.hs -- -- Would look like: --- @("foo", Right ("bar.hs", "module Banana ...") :| [])@ +-- @("foo", Right ("bar.hs", "module Banana …") :| [])@ type Directory μ Directory = (Label, NonEmpty (Either Directory File)) @@ -64,7 +64,7 @@ type DirectoryContents μ DirectoryContents = IsRepo | Directory | File -- Opaque representation of repository state directories (e.g. `.git`, `.pijul`) --- Those are not browseable, but have to be present at the repo root 'Directory'. +-- Those are not browsable, but have to be present at the repo root 'Directory'. type IsRepo -- A Directory captures its own Label followed by 1 or more DirectoryContents @@ -91,7 +91,7 @@ type SystemType = IsFile | IsDirectory --- A Chnage is an enumeration of how a file has changed. +-- A Change is an enumeration of how a file has changed. -- This is simply used for getting the difference between two -- directories. type Change diff --git a/crates/radicle-surf/docs/refactor-design.md b/crates/radicle-surf/docs/refactor-design.md index aac67c084..b861c93d6 100644 --- a/crates/radicle-surf/docs/refactor-design.md +++ b/crates/radicle-surf/docs/refactor-design.md @@ -1,7 +1,7 @@ # An updated design for radicle-surf This is a design blueprint for the new `radicle-git/radicle-surf` crate. The -actual design details and implemenation are described and updated in its +actual design details and implementation are described and updated in its documentation comments, viewable via `cargo doc`. ## Introduction @@ -16,7 +16,7 @@ UI for a git repo: 2. Diff between two revisions that resolve into two commits. 3. Retrieve the history of commits with a given head, and optionally a file. 4. List refs and retrieve their metadata: Branches, Tags, Remotes, -Notes and user-defined "categories", where a category is: `refs//<...>`. +Notes and user-defined "categories", where a category is: `refs//<…>`. ## Motivation @@ -107,7 +107,7 @@ Currently we have multiple types to identify a `Commit` or `Revision`. The relations between them are: all `Rev` and `Commit` can resolve into `Oid`, and in most cases `Rev` can resolve into `Commit`. -On one hand, `Oid` is the ultimate unique identifer but it is more machine- +On one hand, `Oid` is the ultimate unique identifier but it is more machine- friendly than human-friendly. On the other hand, `Revision` is most human- friendly and better suited in the API interface. A conversion from `Revision` to `Oid` will be useful. @@ -138,7 +138,7 @@ Our API will use these traits where we expect a `Revision` or a `Commit`. The current `History` is generic over VCS types and also retrieves the full list of commits when the history is created. The VCS part can be removed and the -history can lazy-load the list of commits by implmenting `Iterator` to support +history can lazy-load the list of commits by implementing `Iterator` to support potentially very long histories. We can also store the head commit with the history so that it's easy to get @@ -288,7 +288,7 @@ pub struct History<'a> { } impl<'a> History<'a> { - /// This method creats a new `RevWalk` internally and return an + /// This method creates a new `RevWalk` internally and return an /// iterator for all commits in a history. pub fn iter(&self) -> impl Iterator; } diff --git a/crates/radicle-surf/examples/browsing.rs b/crates/radicle-surf/examples/browsing.rs index a5206bbdf..bd00ec651 100644 --- a/crates/radicle-surf/examples/browsing.rs +++ b/crates/radicle-surf/examples/browsing.rs @@ -8,8 +8,8 @@ //! the directories in a tree-like structure. use radicle_surf::{ - fs::{self, Directory}, Repository, + fs::{self, Directory}, }; use std::{env, time::Instant}; @@ -33,12 +33,12 @@ fn main() { fn print_directory(d: &Directory, repo: &Repository, indent_level: usize) { let indent = " ".repeat(indent_level * 4); - println!("{}{}/", &indent, d.name()); + println!("{}{}/", indent, d.name()); for entry in d.entries(repo).unwrap() { match entry { - fs::Entry::File(f) => println!(" {}{}", &indent, f.name()), + fs::Entry::File(f) => println!(" {}{}", indent, f.name()), fs::Entry::Directory(d) => print_directory(&d, repo, indent_level + 1), - fs::Entry::Submodule(s) => println!(" {}{}", &indent, s.name()), + fs::Entry::Submodule(s) => println!(" {}{}", indent, s.name()), } } } diff --git a/crates/radicle-surf/examples/diff.rs b/crates/radicle-surf/examples/diff.rs index 9454589af..d15a6c7f6 100644 --- a/crates/radicle-surf/examples/diff.rs +++ b/crates/radicle-surf/examples/diff.rs @@ -2,8 +2,8 @@ extern crate radicle_surf; use std::{env::Args, str::FromStr, time::Instant}; -use radicle_git_ext::Oid; -use radicle_surf::{diff::Diff, Repository}; +use radicle_oid::Oid; +use radicle_surf::{Repository, diff::Diff}; fn main() { let options = get_options_or_exit(); @@ -80,7 +80,8 @@ impl Options { \tpath-to-repo: Path to the directory containing .git subdirectory\n\ \tbase-revision: Git commit ID of the base revision (one that will be considered less recent)\n\ \thead-revision: Git commit ID of the head revision (one that will be considered more recent) or 'HEAD' to use current git HEAD\n", - args[0])); + args[0] + )); } let path_to_repo = args[1].clone(); diff --git a/crates/radicle-surf/src/blob.rs b/crates/radicle-surf/src/blob.rs index 427d0ca70..5ad236a3c 100644 --- a/crates/radicle-surf/src/blob.rs +++ b/crates/radicle-surf/src/blob.rs @@ -3,12 +3,12 @@ use std::ops::Deref; -use radicle_git_ext::Oid; +use radicle_oid::Oid; #[cfg(feature = "serde")] use serde::{ - ser::{SerializeStruct as _, Serializer}, Serialize, + ser::{SerializeStruct as _, Serializer}, }; use crate::Commit; diff --git a/crates/radicle-surf/src/branch.rs b/crates/radicle-surf/src/branch.rs index 73fe8fa2b..dac4d3b2f 100644 --- a/crates/radicle-surf/src/branch.rs +++ b/crates/radicle-surf/src/branch.rs @@ -3,7 +3,7 @@ use std::{ str::{self, FromStr}, }; -use git_ext::ref_format::{component, lit, Component, Qualified, RefStr, RefString}; +use radicle_git_ref_format::{Component, Qualified, RefStr, RefString, lit, name::component}; use crate::refs::refstr_join; @@ -295,7 +295,7 @@ impl FromStr for Remote { } pub mod error { - use radicle_git_ext::ref_format::{self, RefString}; + use radicle_git_ref_format::{self, RefString}; use thiserror::Error; #[derive(Debug, Error)] @@ -305,7 +305,7 @@ pub mod error { #[error("the refname '{0}' did not begin with 'refs/heads' or 'refs/remotes'")] NotQualified(String), #[error(transparent)] - RefFormat(#[from] ref_format::Error), + RefFormat(#[from] radicle_git_ref_format::Error), #[error(transparent)] Utf8(#[from] std::str::Utf8Error), } @@ -317,7 +317,7 @@ pub mod error { #[error("the refname '{0}' did not begin with 'refs/heads'")] NotQualified(String), #[error(transparent)] - RefFormat(#[from] ref_format::Error), + RefFormat(#[from] radicle_git_ref_format::Error), #[error(transparent)] Utf8(#[from] std::str::Utf8Error), } @@ -329,7 +329,7 @@ pub mod error { #[error("the refname '{0}' did not begin with 'refs/remotes'")] NotRemotes(RefString), #[error(transparent)] - RefFormat(#[from] ref_format::Error), + RefFormat(#[from] radicle_git_ref_format::Error), #[error(transparent)] Utf8(#[from] std::str::Utf8Error), } diff --git a/crates/radicle-surf/src/commit.rs b/crates/radicle-surf/src/commit.rs index c2ee708bd..6c2225279 100644 --- a/crates/radicle-surf/src/commit.rs +++ b/crates/radicle-surf/src/commit.rs @@ -1,10 +1,10 @@ use std::{convert::TryFrom, str}; -use radicle_git_ext::Oid; +use radicle_oid::Oid; use thiserror::Error; #[cfg(feature = "serde")] -use serde::{ser::SerializeStruct, Deserialize, Deserializer, Serialize, Serializer}; +use serde::{Deserialize, Deserializer, Serialize, Serializer, ser::SerializeStruct}; #[derive(Debug, Error)] pub enum Error { diff --git a/crates/radicle-surf/src/diff.rs b/crates/radicle-surf/src/diff.rs index f0043aed0..071180942 100644 --- a/crates/radicle-surf/src/diff.rs +++ b/crates/radicle-surf/src/diff.rs @@ -8,9 +8,9 @@ use std::{ }; #[cfg(feature = "serde")] -use serde::{ser, ser::SerializeStruct, Serialize, Serializer}; +use serde::{Serialize, Serializer, ser, ser::SerializeStruct}; -use git_ext::Oid; +use radicle_oid::Oid; pub mod git; @@ -257,20 +257,15 @@ impl Serialize for Copied { } #[cfg_attr(feature = "serde", derive(Serialize), serde(rename_all = "camelCase"))] -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, Default)] pub enum EofNewLine { OldMissing, NewMissing, BothMissing, + #[default] NoneMissing, } -impl Default for EofNewLine { - fn default() -> Self { - Self::NoneMissing - } -} - /// A file that was modified within a [`Diff`]. #[cfg_attr(feature = "serde", derive(Serialize), serde(rename_all = "camelCase"))] #[derive(Clone, Debug, PartialEq, Eq)] diff --git a/crates/radicle-surf/src/error.rs b/crates/radicle-surf/src/error.rs index 1a790dc17..fbe887f47 100644 --- a/crates/radicle-surf/src/error.rs +++ b/crates/radicle-surf/src/error.rs @@ -27,7 +27,7 @@ pub enum Error { #[error(transparent)] Namespace(#[from] namespace::Error), #[error(transparent)] - RefFormat(#[from] git_ext::ref_format::Error), + RefFormat(#[from] radicle_git_ref_format::Error), #[error(transparent)] Revision(Box), #[error(transparent)] @@ -36,4 +36,6 @@ pub enum Error { Tags(#[from] refs::error::Tag), #[error(transparent)] Repo(#[from] repo::error::Repo), + #[error(transparent)] + Oid(#[from] radicle_oid::str::error::ParseOidError), } diff --git a/crates/radicle-surf/src/fs.rs b/crates/radicle-surf/src/fs.rs index 2cbdf8f67..cf7b16f6a 100644 --- a/crates/radicle-surf/src/fs.rs +++ b/crates/radicle-surf/src/fs.rs @@ -11,8 +11,7 @@ use std::{ }; use git2::Blob; -use radicle_git_ext::{is_not_found_err, Oid}; -use radicle_std_ext::result::ResultExt as _; +use radicle_oid::Oid; use url::Url; use crate::{Repository, Revision}; @@ -186,9 +185,9 @@ impl Iterator for Entries { fn next(&mut self) -> Option { // Can be improved when `pop_first()` is stable for BTreeMap. - let next_key = match self.listing.keys().next() { - Some(k) => k.clone(), - None => return None, + let next_key = { + let k = self.listing.keys().next()?; + k.clone() }; self.listing.remove(&next_key) } @@ -228,7 +227,7 @@ impl Ord for Entry { } impl Entry { - /// Get a label for the `Entriess`, either the name of the [`File`], + /// Get a label for the `Entries`, either the name of the [`File`], /// the name of the [`Directory`], or the name of the [`Submodule`]. pub fn name(&self) -> &String { match self { @@ -300,7 +299,7 @@ impl Entry { /// [git-tree]: https://git-scm.com/book/en/v2/Git-Internals-Git-Objects #[derive(Debug, Clone, PartialEq, Eq)] pub struct Directory { - /// The name of the directoy. + /// The name of the directory. name: String, /// The relative path of the directory, not including the `name`, /// in respect to the root of the git repository. @@ -414,11 +413,13 @@ impl Directory { // Search the path in git2 tree. let path = path.as_ref(); let git2_tree = repo.find_tree(self.id)?; - let entry = git2_tree - .get_path(path) - .or_matches::(is_not_found_err, || { - Err(error::Directory::PathNotFound(path.to_path_buf())) - })?; + let entry = git2_tree.get_path(path).map_err(|err| { + if err.code() == git2::ErrorCode::NotFound { + error::Directory::PathNotFound(path.to_path_buf()) + } else { + err.into() + } + })?; let parent = path .parent() .ok_or_else(|| error::Directory::InvalidPath(path.to_path_buf()))?; diff --git a/crates/radicle-surf/src/glob.rs b/crates/radicle-surf/src/glob.rs index c5b0eb632..5a4b8ad4a 100644 --- a/crates/radicle-surf/src/glob.rs +++ b/crates/radicle-surf/src/glob.rs @@ -1,9 +1,8 @@ use std::marker::PhantomData; -use git_ext::ref_format::{ - self, refname, - refspec::{self, PatternString, QualifiedPattern}, - Qualified, RefStr, RefString, +use radicle_git_ref_format::{ + self, Qualified, RefStr, RefString, pattern, refname, + refspec::{PatternString, QualifiedPattern}, }; use thiserror::Error; @@ -12,7 +11,7 @@ use crate::{Branch, Local, Namespace, Remote, Tag}; #[derive(Debug, Error)] pub enum Error { #[error(transparent)] - RefFormat(#[from] ref_format::Error), + RefFormat(#[from] radicle_git_ref_format::Error), } /// A collection of globs for a git reference type. @@ -51,7 +50,7 @@ impl Glob { impl Glob { /// Creates the `Glob` that matches all `refs/namespaces`. pub fn all_namespaces() -> Self { - Self::namespaces(refspec::pattern!("*")) + Self::namespaces(pattern!("*")) } /// Creates a `Glob` for `refs/namespaces`, starting with `glob`. @@ -101,7 +100,7 @@ impl Extend for Glob { impl Glob { /// Creates a `Glob` that matches all `refs/tags`. pub fn all_tags() -> Self { - Self::tags(refspec::pattern!("*")) + Self::tags(pattern!("*")) } /// Creates a `Glob` for `refs/tags`, starting with `glob`. @@ -150,7 +149,7 @@ impl Extend for Glob { impl Glob { /// Creates the `Glob` that matches all `refs/heads`. pub fn all_heads() -> Self { - Self::heads(refspec::pattern!("*")) + Self::heads(pattern!("*")) } /// Creates a `Glob` for `refs/heads`, starting with `glob`. @@ -224,7 +223,7 @@ impl From> for Glob { impl Glob { /// Creates the `Glob` that matches all `refs/remotes`. pub fn all_remotes() -> Self { - Self::remotes(refspec::pattern!("*")) + Self::remotes(pattern!("*")) } /// Creates a `Glob` for `refs/remotes`, starting with `glob`. @@ -298,7 +297,7 @@ impl From> for Glob { impl Glob> { pub fn all_category>(category: R) -> Self { Self { - globs: vec![Self::qualify_category(category, refspec::pattern!("*"))], + globs: vec![Self::qualify_category(category, pattern!("*"))], glob_type: PhantomData, } } diff --git a/crates/radicle-surf/src/lib.rs b/crates/radicle-surf/src/lib.rs index c577b0651..33472c979 100644 --- a/crates/radicle-surf/src/lib.rs +++ b/crates/radicle-surf/src/lib.rs @@ -15,13 +15,11 @@ //! //! [serde]: https://crates.io/crates/serde -extern crate radicle_git_ext as git_ext; - /// Re-exports. -pub use radicle_git_ext::ref_format; +pub use radicle_git_ref_format; /// Represents an object id in Git. Re-exported from `radicle-git-ext`. -pub type Oid = radicle_git_ext::Oid; +pub type Oid = radicle_oid::Oid; pub mod blob; pub mod diff; @@ -60,3 +58,6 @@ mod refs; mod error; pub use error::Error; + +#[cfg(test)] +pub mod test; diff --git a/crates/radicle-surf/src/namespace.rs b/crates/radicle-surf/src/namespace.rs index 590ff03f1..364e42542 100644 --- a/crates/radicle-surf/src/namespace.rs +++ b/crates/radicle-surf/src/namespace.rs @@ -4,12 +4,11 @@ use std::{ str::{self, FromStr}, }; -use git_ext::ref_format::{ - self, - refspec::{NamespacedPattern, PatternString, QualifiedPattern}, - Component, Namespaced, Qualified, RefStr, RefString, -}; use nonempty::NonEmpty; +use radicle_git_ref_format::{ + self, Component, Namespaced, Qualified, RefStr, RefString, + refspec::{NamespacedPattern, PatternString, QualifiedPattern}, +}; use thiserror::Error; #[derive(Debug, Error)] @@ -19,7 +18,7 @@ pub enum Error { #[error("namespaces must not be empty")] EmptyNamespace, #[error(transparent)] - RefFormat(#[from] ref_format::Error), + RefFormat(#[from] radicle_git_ref_format::Error), #[error(transparent)] Utf8(#[from] str::Utf8Error), } diff --git a/crates/radicle-surf/src/refs.rs b/crates/radicle-surf/src/refs.rs index e0b9d71c4..3d94398fd 100644 --- a/crates/radicle-surf/src/refs.rs +++ b/crates/radicle-surf/src/refs.rs @@ -2,13 +2,13 @@ // using Generic associated types supported in Rust 1.65.0. use std::{ - collections::{btree_set, BTreeSet}, + collections::{BTreeSet, btree_set}, convert::TryFrom as _, }; -use git_ext::ref_format::{self, lit, name::Components, Component, Qualified, RefString}; +use radicle_git_ref_format::{self, Component, Qualified, RefString, lit, name::Components}; -use crate::{tag, Branch, Namespace, Tag}; +use crate::{Branch, Namespace, Tag, tag}; /// Iterator over [`Tag`]s. #[derive(Default)] @@ -66,7 +66,7 @@ impl Iterator for TagNames<'_> { tag::reference_name(&r) .map(|name| lit::refs_tags(name).into()) .map_err(error::Tag::from) - })) + })); } None => self.inner.current += 1, }, @@ -110,7 +110,7 @@ impl Iterator for Branches<'_> { return Some( res.map_err(error::Branch::from) .and_then(|r| Branch::try_from(&r).map_err(error::Branch::from)), - ) + ); } None => self.current += 1, }, @@ -133,7 +133,7 @@ impl Iterator for BranchNames<'_> { Branch::try_from(&r) .map(|branch| branch.refname().into_owned()) .map_err(error::Branch::from) - })) + })); } None => self.inner.current += 1, }, @@ -187,7 +187,7 @@ impl Iterator for Categories<'_> { Some(res) => { return Some(res.map_err(error::Category::from).and_then(|r| { let name = std::str::from_utf8(r.name_bytes())?; - let name = ref_format::RefStr::try_from_str(name)?; + let name = radicle_git_ref_format::RefStr::try_from_str(name)?; let name = name.qualified().ok_or_else(|| { error::Category::NotQualified(name.to_ref_string()) })?; @@ -207,7 +207,7 @@ impl Iterator for Categories<'_> { pub mod error { use std::str; - use radicle_git_ext::ref_format::{self, RefString}; + use radicle_git_ref_format::{self, RefString}; use thiserror::Error; use crate::{branch, tag}; @@ -227,7 +227,7 @@ pub mod error { #[error("the reference '{0}' was expected to be qualified, i.e. 'refs//'")] NotQualified(RefString), #[error(transparent)] - RefFormat(#[from] ref_format::Error), + RefFormat(#[from] radicle_git_ref_format::Error), #[error(transparent)] Utf8(#[from] str::Utf8Error), } diff --git a/crates/radicle-surf/src/repo.rs b/crates/radicle-surf/src/repo.rs index 162d24876..cf52cb821 100644 --- a/crates/radicle-surf/src/repo.rs +++ b/crates/radicle-surf/src/repo.rs @@ -5,18 +5,16 @@ use std::{ str, }; -use git_ext::{ - ref_format::{refspec::QualifiedPattern, Qualified, RefStr, RefString}, - Oid, -}; +use radicle_git_ref_format::{Qualified, RefStr, RefString, refspec::QualifiedPattern}; +use radicle_oid::Oid; use crate::{ + Branch, Commit, Error, Glob, History, Namespace, Revision, Signature, Stats, Tag, ToCommit, blob::{Blob, BlobRef}, diff::{Diff, FileDiff}, fs::{Directory, File, FileContent}, refs::{BranchNames, Branches, Categories, Namespaces, TagNames, Tags}, tree::{Entry, Tree}, - Branch, Commit, Error, Glob, History, Namespace, Revision, Signature, Stats, Tag, ToCommit, }; /// Enumeration of errors that can occur in repo operations. @@ -373,7 +371,7 @@ impl Repository { .to_commit(self) .map_err(|e| Error::ToCommit(e.into()))?; - match self.inner.extract_signature(&commit.id, field) { + match self.inner.extract_signature(&commit.id.into(), field) { Err(error) => { if error.code() == git2::ErrorCode::NotFound { Ok(None) diff --git a/crates/radicle-surf/src/revision.rs b/crates/radicle-surf/src/revision.rs index 4e34f63f9..b9ab8b4a1 100644 --- a/crates/radicle-surf/src/revision.rs +++ b/crates/radicle-surf/src/revision.rs @@ -1,9 +1,7 @@ use std::convert::Infallible; -use git_ext::{ - ref_format::{Qualified, RefString}, - Oid, -}; +use radicle_git_ref_format::{Qualified, RefString}; +use radicle_oid::Oid; use crate::{Branch, Commit, Error, Repository, Tag}; @@ -50,10 +48,13 @@ impl Revision for Oid { } impl Revision for &str { - type Error = git2::Error; + type Error = radicle_oid::str::error::ParseOidError; - fn object_id(&self, repo: &Repository) -> Result { - Oid::from_str_ext(self, repo.object_format()) + fn object_id(&self, _repo: &Repository) -> Result { + use std::str::FromStr as _; + + // TODO: Support for SHA-256. + Oid::from_str(self) } } @@ -75,10 +76,10 @@ impl Revision for Tag { } impl Revision for String { - type Error = git2::Error; + type Error = radicle_oid::str::error::ParseOidError; fn object_id(&self, repo: &Repository) -> Result { - Oid::from_str_ext(self, repo.object_format()) + self.as_str().object_id(repo) } } diff --git a/crates/radicle-surf/src/tag.rs b/crates/radicle-surf/src/tag.rs index daad8b729..ed1f54e09 100644 --- a/crates/radicle-surf/src/tag.rs +++ b/crates/radicle-surf/src/tag.rs @@ -1,11 +1,9 @@ use std::{convert::TryFrom, str}; -use git_ext::{ - ref_format::{component, lit, Qualified, RefStr, RefString}, - Oid, -}; +use radicle_git_ref_format::{Qualified, RefStr, RefString, lit, name::component}; +use radicle_oid::Oid; -use crate::{refs::refstr_join, Author}; +use crate::{Author, refs::refstr_join}; /// The metadata of a [`Git tag`][git-tag]. /// @@ -62,13 +60,13 @@ impl Tag { pub mod error { use std::str; - use radicle_git_ext::ref_format::{self, RefString}; + use radicle_git_ref_format::{self, RefString}; use thiserror::Error; #[derive(Debug, Error)] pub enum FromTag { #[error(transparent)] - RefFormat(#[from] ref_format::Error), + RefFormat(#[from] radicle_git_ref_format::Error), #[error(transparent)] Utf8(#[from] str::Utf8Error), } @@ -84,7 +82,7 @@ pub mod error { #[error("the refname '{0}' did not begin with 'refs/tags'")] NotTag(RefString), #[error(transparent)] - RefFormat(#[from] ref_format::Error), + RefFormat(#[from] radicle_git_ref_format::Error), #[error(transparent)] Utf8(#[from] str::Utf8Error), } diff --git a/crates/radicle-surf/src/test/branch.rs b/crates/radicle-surf/src/test/branch.rs index ae4e62d4f..ef8322e11 100644 --- a/crates/radicle-surf/src/test/branch.rs +++ b/crates/radicle-surf/src/test/branch.rs @@ -1,20 +1,19 @@ +use super::r#gen; +use crate::Branch; use proptest::prelude::*; -use radicle_git_ext::ref_format::{RefStr, RefString}; -use radicle_git_ext_test::git_ref_format::gen; -use radicle_surf::Branch; -use test_helpers::roundtrip; +use radicle_git_ref_format::{RefStr, RefString}; proptest! { #[test] fn prop_test_branch(branch in gen_branch()) { - roundtrip::json(branch) + super::roundtrip::json(branch) } } fn gen_branch() -> impl Strategy { prop_oneof![ - gen::valid().prop_map(|name| Branch::local(RefString::try_from(name).unwrap())), - (gen::valid(), gen::valid()).prop_map(|(remote, name): (String, String)| { + r#gen::valid().prop_map(|name| Branch::local(RefString::try_from(name).unwrap())), + (r#gen::valid(), r#gen::valid()).prop_map(|(remote, name): (String, String)| { let remote = RefStr::try_from_str(&remote).expect("BUG: reference strings should be valid"); let name = RefStr::try_from_str(&name).expect("BUG: reference strings should be valid"); diff --git a/crates/radicle-surf/src/test/code_browsing.rs b/crates/radicle-surf/src/test/code_browsing.rs index 3cafcde3c..8760eb9e5 100644 --- a/crates/radicle-surf/src/test/code_browsing.rs +++ b/crates/radicle-surf/src/test/code_browsing.rs @@ -1,16 +1,16 @@ use std::path::Path; -use radicle_git_ext::ref_format::refname; -use radicle_surf::{ - fs::{self, Directory}, +use crate::{ Branch, Repository, + fs::{self, Directory}, }; +use radicle_git_ref_format::refname; -use super::GIT_PLATINUM; +use super::platinum; #[test] fn iterate_root_dir_recursive() { - let repo = Repository::open(GIT_PLATINUM).unwrap(); + let repo = Repository::open(platinum::get()).unwrap(); let root_dir = repo.root_dir(Branch::local(refname!("master"))).unwrap(); let count = println_dir(&root_dir, &repo); @@ -41,7 +41,7 @@ fn iterate_root_dir_recursive() { #[test] fn browse_repo_lazily() { - let repo = Repository::open(GIT_PLATINUM).unwrap(); + let repo = Repository::open(platinum::get()).unwrap(); let root_dir = repo.root_dir(Branch::local(refname!("master"))).unwrap(); let count = root_dir.entries(&repo).unwrap().entries().count(); @@ -57,7 +57,7 @@ fn browse_repo_lazily() { #[test] fn test_file_history() { - let repo = Repository::open(GIT_PLATINUM).unwrap(); + let repo = Repository::open(platinum::get()).unwrap(); let history = repo.history(Branch::local(refname!("dev"))).unwrap(); let path = Path::new("README.md"); let mut file_history = history.by_path(&path); @@ -68,7 +68,7 @@ fn test_file_history() { #[test] fn test_commit_history() { - let repo = Repository::open(GIT_PLATINUM).unwrap(); + let repo = Repository::open(platinum::get()).unwrap(); let head = "a0dd9122d33dff2a35f564d564db127152c88e02"; // verify `&str` works. @@ -83,7 +83,7 @@ fn test_commit_history() { #[test] fn test_commit_signature() { - let repo = Repository::open(GIT_PLATINUM).unwrap(); + let repo = Repository::open(platinum::get()).unwrap(); let commit_with_signature = "e24124b7538658220b5aaf3b6ef53758f0a106dc"; let signature = repo.extract_signature(commit_with_signature, None).unwrap(); assert!(signature.is_some()); diff --git a/crates/radicle-surf/src/test/commit.rs b/crates/radicle-surf/src/test/commit.rs index b0a722264..073cc24e7 100644 --- a/crates/radicle-surf/src/test/commit.rs +++ b/crates/radicle-surf/src/test/commit.rs @@ -1,14 +1,13 @@ use std::str::FromStr; +use crate::{Author, Commit, Time}; use proptest::prelude::*; -use radicle_git_ext::Oid; -use radicle_surf::{Author, Commit, Time}; -use test_helpers::roundtrip; +use radicle_oid::Oid; proptest! { #[test] fn prop_test_commits(commit in commits_strategy()) { - roundtrip::json(commit) + super::roundtrip::json(commit) } } diff --git a/crates/radicle-surf/src/test/diff.rs b/crates/radicle-surf/src/test/diff.rs index 292df46f3..263c8e3c5 100644 --- a/crates/radicle-surf/src/test/diff.rs +++ b/crates/radicle-surf/src/test/diff.rs @@ -1,19 +1,21 @@ -use pretty_assertions::assert_eq; -use radicle_git_ext::{ref_format::refname, Oid}; -use radicle_surf::{ +use std::{path::Path, str::FromStr}; + +use radicle_git_ref_format::refname; +use radicle_oid::Oid; + +use crate::{ + Branch, Error, Repository, diff::{ Added, Diff, DiffContent, DiffFile, EofNewLine, FileDiff, FileMode, FileStats, Hunk, Line, Modification, Modified, Stats, }, - Branch, Error, Repository, }; -use std::{path::Path, str::FromStr}; -use super::GIT_PLATINUM; +use super::platinum; #[test] fn test_initial_diff() -> Result<(), Error> { - let repo = Repository::open(GIT_PLATINUM)?; + let repo = Repository::open(platinum::get())?; let oid = Oid::from_str("d3464e33d75c75c99bfb90fa2e9d16efc0b7d0e3")?; let commit = repo.commit(oid).unwrap(); assert!(commit.parents.is_empty()); @@ -62,7 +64,7 @@ fn test_initial_diff() -> Result<(), Error> { #[test] fn test_diff_of_rev() -> Result<(), Error> { - let repo = Repository::open(GIT_PLATINUM)?; + let repo = Repository::open(platinum::get())?; let diff = repo.diff_commit("80bacafba303bf0cdf6142921f430ff265f25095")?; assert_eq!(diff.files().count(), 1); Ok(()) @@ -70,7 +72,7 @@ fn test_diff_of_rev() -> Result<(), Error> { #[test] fn test_diff_file() -> Result<(), Error> { - let repo = Repository::open(GIT_PLATINUM)?; + let repo = Repository::open(platinum::get())?; let path_buf = Path::new("README.md").to_path_buf(); let diff = repo.diff_file( &path_buf, @@ -113,7 +115,7 @@ fn test_diff_file() -> Result<(), Error> { #[test] fn test_diff() -> Result<(), Error> { - let repo = Repository::open(GIT_PLATINUM)?; + let repo = Repository::open(platinum::get())?; let oid = "80bacafba303bf0cdf6142921f430ff265f25095"; let commit = repo.commit(oid).unwrap(); let parent_oid = commit.parents.first().unwrap(); @@ -163,7 +165,7 @@ fn test_diff() -> Result<(), Error> { #[test] fn test_branch_diff() -> Result<(), Error> { - let repo = Repository::open(GIT_PLATINUM)?; + let repo = Repository::open(platinum::get())?; let rev_from = Branch::local(refname!("master")); let rev_to = Branch::local(refname!("dev")); let diff = repo.diff(&rev_from, &rev_to)?; @@ -181,16 +183,16 @@ fn test_branch_diff() -> Result<(), Error> { assert_eq!(diff.moved().count(), 1); assert_eq!(diff.modified().count(), 2); for c in diff.added() { - println!("added: {:?}", &c.path); + println!("added: {:?}", c.path); } for d in diff.deleted() { - println!("deleted: {:?}", &d.path); + println!("deleted: {:?}", d.path); } for m in diff.moved() { - println!("moved: {:?} -> {:?}", &m.old_path, &m.new_path); + println!("moved: {:?} -> {:?}", m.old_path, m.new_path); } for m in diff.modified() { - println!("modified: {:?}", &m.path); + println!("modified: {:?}", m.path); } // Verify moved. @@ -198,11 +200,11 @@ fn test_branch_diff() -> Result<(), Error> { // We can find a `FileDiff` for the old_path in a move. let file_diff = repo.diff_file(&diff_moved.old_path, &rev_from, &rev_to)?; - println!("old path file diff: {:?}", &file_diff); + println!("old path file diff: {:?}", file_diff); // We can find a `FileDiff` for the new_path in a move. let file_diff = repo.diff_file(&diff_moved.new_path, &rev_from, &rev_to)?; - println!("new path file diff: {:?}", &file_diff); + println!("new path file diff: {:?}", file_diff); // We can find a `FileDiff` if given a directory name. let dir_diff = repo.diff_file(&"special/", &rev_from, &rev_to)?; @@ -211,9 +213,10 @@ fn test_branch_diff() -> Result<(), Error> { Ok(()) } +#[cfg(feature = "serde")] #[test] fn test_diff_serde() -> Result<(), Error> { - let repo = Repository::open(GIT_PLATINUM)?; + let repo = Repository::open(platinum::get())?; let rev_from = Branch::local(refname!("master")); let rev_to = Branch::local(refname!("diff-test")); let diff = repo.diff(rev_from, rev_to)?; @@ -380,6 +383,7 @@ fn test_diff_serde() -> Result<(), Error> { Ok(()) } +#[cfg(feature = "serde")] #[test] fn test_rename_with_changes() { let buf = r" diff --git a/crates/radicle-surf/src/test/file_system.rs b/crates/radicle-surf/src/test/file_system.rs index bf6150599..5368bdc17 100644 --- a/crates/radicle-surf/src/test/file_system.rs +++ b/crates/radicle-surf/src/test/file_system.rs @@ -1,18 +1,16 @@ -//! Unit tests for radicle_surf::file_system - -mod directory { - use radicle_git_ext::ref_format::refname; - use radicle_surf::{ - fs::{self, Entry}, +pub mod directory { + use crate::{ Branch, Oid, Repository, + fs::{self, Entry}, + test::platinum, }; + use git2::RepositoryInitOptions; + use radicle_git_ref_format::refname; use std::path::Path; - const GIT_PLATINUM: &str = "../data/git-platinum"; - #[test] fn directory_find_entry() { - let repo = Repository::open(GIT_PLATINUM).unwrap(); + let repo = Repository::open(platinum::get()).unwrap(); let root = repo.root_dir(Branch::local(refname!("master"))).unwrap(); // find_entry for a file. @@ -53,7 +51,7 @@ mod directory { #[test] fn directory_find_file_and_directory() { - let repo = Repository::open(GIT_PLATINUM).unwrap(); + let repo = Repository::open(platinum::get()).unwrap(); // Get the snapshot of the directory for a given commit. let root = repo .root_dir("80ded66281a4de2889cc07293a8f10947c6d57fe") @@ -91,7 +89,7 @@ mod directory { #[test] fn directory_size() { - let repo = Repository::open(GIT_PLATINUM).unwrap(); + let repo = Repository::open(platinum::get()).unwrap(); let root = repo.root_dir(Branch::local(refname!("master"))).unwrap(); /* @@ -112,7 +110,7 @@ mod directory { #[test] fn directory_last_commit() { - let repo = Repository::open(GIT_PLATINUM).unwrap(); + let repo = Repository::open(platinum::get()).unwrap(); let branch = Branch::local(refname!("dev")); let root = repo.root_dir(&branch).unwrap(); let dir = root.find_directory(&"this/is", &repo).unwrap(); @@ -125,7 +123,7 @@ mod directory { #[test] fn file_last_commit() { - let repo = Repository::open(GIT_PLATINUM).unwrap(); + let repo = Repository::open(platinum::get()).unwrap(); let branch = Branch::local(refname!("master")); let root = repo.root_dir(&branch).unwrap(); @@ -145,9 +143,11 @@ mod directory { /// interpreted as glob patterns by git's pathspec, causing errors. #[test] fn directory_with_bracket_in_name() { - let repo = test_helpers::tempdir::WithTmpDir::new(|path| { - git2::Repository::init(path).map_err(std::io::Error::other) - }) + let path = tempfile::TempDir::new().unwrap(); + let repo = git2::Repository::init_opts( + path.path().join("repo"), + RepositoryInitOptions::new().initial_head("master"), + ) .unwrap(); // Initialize the repo and create test structure: diff --git a/crates/radicle-surf/src/test/gen.rs b/crates/radicle-surf/src/test/gen.rs new file mode 100644 index 000000000..c43160186 --- /dev/null +++ b/crates/radicle-surf/src/test/gen.rs @@ -0,0 +1,22 @@ +pub(crate) mod commit; + +use proptest::prelude::*; + +/// Any unicode "word" is trivially a valid refname. +#[cfg(feature = "serde")] +pub fn trivial() -> impl Strategy { + "\\w+" +} + +#[cfg(feature = "serde")] +pub fn valid() -> impl Strategy { + prop::collection::vec(trivial(), 1..20).prop_map(|xs| xs.join("/")) +} + +pub fn alphanumeric() -> impl Strategy { + "[a-zA-Z0-9_]+" +} + +pub fn alpha() -> impl Strategy { + "[a-zA-Z]+" +} diff --git a/crates/radicle-surf/src/test/gen/commit.rs b/crates/radicle-surf/src/test/gen/commit.rs new file mode 100644 index 000000000..96416ef7b --- /dev/null +++ b/crates/radicle-surf/src/test/gen/commit.rs @@ -0,0 +1,102 @@ +use std::convert::Infallible; + +use proptest::strategy::Strategy; +use radicle_git_metadata::commit::CommitData; + +mod author; +mod headers; +mod trailers; + +pub use author::author; +pub use headers::headers; +pub use trailers::trailers; + +use super::alphanumeric; + +pub fn commit() -> impl Strategy> { + ( + TreeData::r#gen(), + author(), + author(), + headers(), + alphanumeric(), + trailers(3), + ) + .prop_map(|(tree, author, committer, headers, message, trailers)| { + CommitData::new(tree, vec![], author, committer, headers, message, trailers) + }) +} + +pub fn write_commits( + repo: &git2::Repository, + linear: Vec>, +) -> Result, git2::Error> { + let mut parent = None; + let mut commits = Vec::new(); + for commit in linear { + let commit = commit.map_tree(|tree| tree.write(repo))?; + let commit = match parent { + Some(parent) => commit + .map_parents::(|_| Ok(parent)) + .unwrap(), + None => commit + .map_parents::(|_| unreachable!("no parents")) + .unwrap(), + }; + let tree = repo.find_tree(*commit.tree())?; + let oid = repo.commit( + None, + &git2::Signature::try_from(commit.author()).unwrap(), + &git2::Signature::try_from(commit.committer()).unwrap(), + commit.message(), + &tree, + &[], + )?; + commits.push(oid); + parent = Some(oid); + } + Ok(commits) +} + +#[derive(Clone, Debug)] +pub enum TreeData { + Blob { name: String, data: String }, + Tree { name: String, inner: Vec }, +} + +impl TreeData { + fn r#gen() -> impl Strategy { + let leaf = + (alphanumeric(), alphanumeric()).prop_map(|(name, data)| Self::Blob { name, data }); + leaf.prop_recursive(8, 16, 5, |inner| { + (proptest::collection::vec(inner, 1..5), alphanumeric()) + .prop_map(|(inner, name)| Self::Tree { name, inner }) + }) + } + + fn write(&self, repo: &git2::Repository) -> Result { + let mut builder = repo.treebuilder(None)?; + self.write_(repo, &mut builder)?; + builder.write() + } + + fn write_( + &self, + repo: &git2::Repository, + builder: &mut git2::TreeBuilder, + ) -> Result { + match self { + Self::Blob { name, data } => { + let oid = repo.blob(data.as_bytes())?; + builder.insert(name, oid, git2::FileMode::Blob.into())?; + } + Self::Tree { name, inner } => { + for data in inner { + let oid = data.write_(repo, builder)?; + builder.insert(name, oid, git2::FileMode::Tree.into())?; + } + } + } + builder.write() + } +} diff --git a/crates/radicle-surf/src/test/gen/commit/author.rs b/crates/radicle-surf/src/test/gen/commit/author.rs new file mode 100644 index 000000000..fb38bd236 --- /dev/null +++ b/crates/radicle-surf/src/test/gen/commit/author.rs @@ -0,0 +1,19 @@ +use proptest::strategy::{Just, Strategy}; +use radicle_git_metadata::author::{Author, Time}; + +use crate::test::r#gen; + +pub fn author() -> impl Strategy { + r#gen::alphanumeric().prop_flat_map(move |name| { + (Just(name), r#gen::alphanumeric()).prop_flat_map(|(name, domain)| { + (Just(name), Just(domain), (0..1000i64)).prop_map(move |(name, domain, time)| { + let email = format!("{name}@{domain}"); + Author { + name, + email, + time: Time::new(time, 0), + } + }) + }) + }) +} diff --git a/crates/radicle-surf/src/test/gen/commit/headers.rs b/crates/radicle-surf/src/test/gen/commit/headers.rs new file mode 100644 index 000000000..80ecfee4a --- /dev/null +++ b/crates/radicle-surf/src/test/gen/commit/headers.rs @@ -0,0 +1,30 @@ +use proptest::{collection, prop_oneof, strategy::Strategy}; +use radicle_git_metadata::commit::headers::Headers; + +use crate::test::r#gen; + +pub fn headers() -> impl Strategy { + collection::vec(prop_oneof![header(), signature()], 0..5).prop_map(|hs| { + let mut headers = Headers::new(); + for (k, v) in hs { + headers.push(&k, &v); + } + headers + }) +} + +fn header() -> impl Strategy { + (prop_oneof!["test", "foo", "foobar"], r#gen::alphanumeric()) +} + +pub fn signature() -> impl Strategy { + ("gpgsig", prop_oneof![pgp(), ssh()]) +} + +pub fn pgp() -> impl Strategy { + "-----BEGIN PGP SIGNATURE-----\r?\n([A-Za-z0-9+/=\r\n]+)\r?\n-----END PGP SIGNATURE-----" +} + +pub fn ssh() -> impl Strategy { + "-----BEGIN SSH SIGNATURE-----\r?\n([A-Za-z0-9+/=\r\n]+)\r?\n-----END SSH SIGNATURE-----" +} diff --git a/crates/radicle-surf/src/test/gen/commit/trailers.rs b/crates/radicle-surf/src/test/gen/commit/trailers.rs new file mode 100644 index 000000000..2881a729c --- /dev/null +++ b/crates/radicle-surf/src/test/gen/commit/trailers.rs @@ -0,0 +1,18 @@ +use proptest::{collection, strategy::Strategy}; +use radicle_git_metadata::commit::trailers::{OwnedTrailer, Token, Trailer}; + +use crate::test::r#gen; + +pub fn trailers(n: usize) -> impl Strategy> { + collection::vec(trailer(), 0..n) +} + +pub fn trailer() -> impl Strategy { + (r#gen::alpha(), r#gen::alphanumeric()).prop_map(|(token, value)| { + Trailer { + token: Token::try_from(format!("X-{}", token).as_str()).unwrap(), + value: value.into(), + } + .to_owned() + }) +} diff --git a/crates/radicle-surf/src/test/last_commit.rs b/crates/radicle-surf/src/test/last_commit.rs index 009893ee9..30669c2d4 100644 --- a/crates/radicle-surf/src/test/last_commit.rs +++ b/crates/radicle-surf/src/test/last_commit.rs @@ -1,18 +1,19 @@ use std::{path::PathBuf, str::FromStr}; -use radicle_git_ext::{ref_format::refname, Oid}; -use radicle_surf::{Branch, Repository}; +use radicle_git_ref_format::refname; +use radicle_oid::Oid; -use super::GIT_PLATINUM; +use crate::{Branch, Repository}; + +use super::platinum; #[test] fn readme_missing_and_memory() { - let repo = Repository::open(GIT_PLATINUM) - .expect("Could not retrieve ./data/git-platinum as git repository"); + let repo = Repository::open(platinum::get()).unwrap(); let oid = Oid::from_str("d3464e33d75c75c99bfb90fa2e9d16efc0b7d0e3").expect("Failed to parse SHA"); - // memory.rs is commited later so it should not exist here. + // memory.rs is committed later so it should not exist here. let memory_last_commit_oid = repo .last_commit(&"src/memory.rs", oid) .expect("Failed to get last commit") @@ -31,8 +32,7 @@ fn readme_missing_and_memory() { #[test] fn folder_svelte() { - let repo = Repository::open(GIT_PLATINUM) - .expect("Could not retrieve ./data/git-platinum as git repository"); + let repo = Repository::open(platinum::get()).unwrap(); // Check that last commit is the actual last commit even if head commit differs. let oid = Oid::from_str("19bec071db6474af89c866a1bd0e4b1ff76e2b97").expect("Could not parse SHA"); @@ -49,8 +49,7 @@ fn folder_svelte() { #[test] fn nest_directory() { - let repo = Repository::open(GIT_PLATINUM) - .expect("Could not retrieve ./data/git-platinum as git repository"); + let repo = Repository::open(platinum::get()).unwrap(); // Check that last commit is the actual last commit even if head commit differs. let oid = Oid::from_str("19bec071db6474af89c866a1bd0e4b1ff76e2b97").expect("Failed to parse SHA"); @@ -68,8 +67,7 @@ fn nest_directory() { #[test] #[cfg(not(windows))] fn can_get_last_commit_for_special_filenames() { - let repo = Repository::open(GIT_PLATINUM) - .expect("Could not retrieve ./data/git-platinum as git repository"); + let repo = Repository::open(platinum::get()).unwrap(); // Check that last commit is the actual last commit even if head commit differs. let oid = @@ -92,8 +90,7 @@ fn can_get_last_commit_for_special_filenames() { #[test] fn root() { - let repo = Repository::open(GIT_PLATINUM) - .expect("Could not retrieve ./data/git-platinum as git repository"); + let repo = Repository::open(platinum::get()).unwrap(); let rev = Branch::local(refname!("master")); let root_last_commit_id = repo .last_commit(&PathBuf::new(), rev) @@ -110,10 +107,9 @@ fn root() { #[test] fn binary_file() { - let repo = Repository::open(GIT_PLATINUM) - .expect("Could not retrieve ./data/git-platinum as git repository"); + let repo = Repository::open(platinum::get()).unwrap(); let history = repo.history(Branch::local(refname!("dev"))).unwrap(); let file_commit = history.by_path(&"bin/cat").next(); assert!(file_commit.is_some()); - println!("file commit: {:?}", &file_commit); + println!("file commit: {:?}", file_commit); } diff --git a/crates/radicle-surf/src/test/mod.rs b/crates/radicle-surf/src/test/mod.rs new file mode 100644 index 000000000..f63186925 --- /dev/null +++ b/crates/radicle-surf/src/test/mod.rs @@ -0,0 +1,20 @@ +#[cfg(feature = "serde")] +mod branch; +mod code_browsing; +#[cfg(feature = "serde")] +mod commit; +mod diff; +mod file_system; +mod r#gen; +mod last_commit; +mod namespace; +mod platinum; +mod reference; +mod repository; +mod rev; +#[cfg(feature = "serde")] +mod roundtrip; +#[cfg(feature = "serde")] +mod source; +mod submodule; +mod threading; diff --git a/crates/radicle-surf/src/test/namespace.rs b/crates/radicle-surf/src/test/namespace.rs index 0fe7b74c1..0e8a3dc31 100644 --- a/crates/radicle-surf/src/test/namespace.rs +++ b/crates/radicle-surf/src/test/namespace.rs @@ -1,12 +1,12 @@ -use pretty_assertions::{assert_eq, assert_ne}; -use radicle_git_ext::ref_format::{name::component, refname, refspec}; -use radicle_surf::{Branch, Error, Glob, Repository}; +use radicle_git_ref_format::{component, pattern, refname}; -use super::GIT_PLATINUM; +use crate::{Branch, Error, Glob, Repository}; + +use super::platinum; #[test] fn switch_to_banana() -> Result<(), Error> { - let repo = Repository::open(GIT_PLATINUM)?; + let repo = Repository::open(platinum::get())?; let history_master = repo.history(Branch::local(refname!("master")))?; repo.switch_namespace(&refname!("golden"))?; let history_banana = repo.history(Branch::local(refname!("banana")))?; @@ -18,7 +18,7 @@ fn switch_to_banana() -> Result<(), Error> { #[test] fn me_namespace() -> Result<(), Error> { - let repo = Repository::open(GIT_PLATINUM)?; + let repo = Repository::open(platinum::get())?; let history = repo.history(Branch::local(refname!("master")))?; assert_eq!(repo.which_namespace().unwrap(), None); @@ -42,7 +42,7 @@ fn me_namespace() -> Result<(), Error> { refname!("heads/feature/#1194"), )]; let mut branches = repo - .branches(Glob::remotes(refspec::pattern!("fein/*")))? + .branches(Glob::remotes(pattern!("fein/*")))? .collect::, _>>()?; branches.sort(); @@ -53,7 +53,7 @@ fn me_namespace() -> Result<(), Error> { #[test] fn golden_namespace() -> Result<(), Error> { - let repo = Repository::open(GIT_PLATINUM)?; + let repo = Repository::open(platinum::get())?; let history = repo.history(Branch::local(refname!("master")))?; assert_eq!(repo.which_namespace().unwrap(), None); @@ -85,7 +85,7 @@ fn golden_namespace() -> Result<(), Error> { Branch::remote(remote, refname!("tags/v0.1.0")), ]; let mut branches = repo - .branches(Glob::remotes(refspec::pattern!("kickflip/*")))? + .branches(Glob::remotes(pattern!("kickflip/*")))? .collect::, _>>()?; branches.sort(); @@ -96,7 +96,7 @@ fn golden_namespace() -> Result<(), Error> { #[test] fn silver_namespace() -> Result<(), Error> { - let repo = Repository::open(GIT_PLATINUM)?; + let repo = Repository::open(platinum::get())?; let history = repo.history(Branch::local(refname!("master")))?; assert_eq!(repo.which_namespace().unwrap(), None); diff --git a/crates/radicle-surf/src/test/platinum.rs b/crates/radicle-surf/src/test/platinum.rs new file mode 100644 index 000000000..73144f12a --- /dev/null +++ b/crates/radicle-surf/src/test/platinum.rs @@ -0,0 +1,708 @@ +use std::{io::Read as _, mem, path::Path, str, sync::LazyLock}; + +use flate2::read::GzDecoder; +use git2::{Oid, Repository, Signature, Time, build::TreeUpdateBuilder}; +use hex_literal::hex; +use tempfile::TempDir; + +static LOCK: LazyLock = LazyLock::new(init); + +pub(crate) fn get() -> &'static Path { + LOCK.path() +} + +macro_rules! oid { + ($bytes:expr) => { + radicle_oid::Oid::Sha1(hex!($bytes)) + }; +} + +#[rustfmt::skip] +mod author { + use super::*; + + pub(super) struct Author { + name: &'static str, + email: &'static str, + } + + impl Author { + const fn new(name: &'static str, email: &'static str) -> Self { + Self { name, email } + } + + pub(super) fn signature(&self, time: &Time) -> git2::Signature<'static> { + Signature::new(self.name, self.email, time).unwrap() + } + } + + pub(super) const ALEXANDER: Author = Author::new("Alexander Simmerl", "a.simmerl@gmail.com" ); + pub(super) const FINTAN_1: Author = Author::new("FintanH", "fintan.halpenny@gmail.com" ); + pub(super) const FINTAN_2: Author = Author::new("Fintan Halpenny", "fintan.halpenny@gmail.com" ); + pub(super) const GITHUB: Author = Author::new("GitHub", "noreply@github.com" ); + const HAN: Author = Author::new("Han Xu", "keepsimple@gmail.com" ); + pub(super) const RUDOLFS: Author = Author::new("Rūdolfs Ošiņš", "rudolfs@osins.org" ); + pub(super) const SEBASTIAN: Author = Author::new("Sebastian Martinez", "me@sebastinez.dev"); + pub(super) const THOMAS: Author = Author::new("Thomas Scholtes", "thomas@monadic.xyz" ); + + pub(super) fn rudolfs(seconds: i64) -> git2::Signature<'static> { + RUDOLFS.signature(&Time::new(seconds, 60)) + } + + pub(super) fn han(seconds: i64) -> git2::Signature<'static> { + HAN.signature(&Time::new(seconds, -480)) + } +} + +use author::*; + +/// Git blobs, represented by their contents and expected object ID, i.e., +/// expected SHA-1 digest of the contents. +/// +/// [`Self::write`] asserts that the actual object ID computed matches +/// [`Blob::oid`], which helps to catch errors in construction/loading of +/// contents early. +struct Blob<'a> { + oid: radicle_oid::Oid, + contents: &'a [u8], +} + +impl<'a> Blob<'a> { + const EMPTY: Blob<'static> = Blob { + oid: oid!("e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"), + contents: &[], + }; + + /// Writes this blob to the object database of `repo`, and asserts that + /// the returned object ID matches [`Self::oid`]. + /// + /// To obtain a handle to the blob in the object database of `repo`, + /// use [`Repository::find_blob`] after [`Self::write`] has returned. + fn write(&self, repo: &Repository) -> Oid { + let oid = repo.blob(self.contents).unwrap(); + assert_eq!(radicle_oid::Oid::from(oid), self.oid); + oid + } + + fn to_vec(&self) -> Vec { + self.contents.to_vec() + } +} + +const README_1: Blob = Blob { + oid: oid!("7f48df0118b1674f4ab0ed1717c1368091a5dddc"), + contents: b"This repository is a data source for the Upstream front-end tests.\n", +}; + +const README_2: Blob = Blob { + oid: oid!("5e07534cd74a6a9b2ccd2729b181c4ef26173a5e"), + contents: b"This repository is a data source for the Upstream front-end tests and the\n[`radicle-surf`](https://github.com/radicle-dev/git-platinum) unit tests.\n", +}; + +const README_3: Blob = Blob { + oid: oid!("b033ecf407a44922b28c942c696922a7d7daf06e"), + contents: b"This repository is a data source for the upstream front-end tests and the\n[`radicle-surf`](https://github.com/radicle-dev/radicle-surf) unit tests.\n", +}; + +const LICENSE: Blob = Blob { + oid: oid!("02f70f56ec62396ceaf38804c37e169e875ab291"), + contents: include_bytes!("platinum/LICENSE"), +}; + +const EVAL: Blob = Blob { + oid: oid!("8c7447d13b907aa994ac3a38317c1e9633bf0732"), + contents: include_bytes!("platinum/Eval.hs"), +}; + +const FOLDER: Blob = Blob { + oid: oid!("a50cdb374f3a16da6cc6056a5f2818b53efdb745"), + contents: include_bytes!("platinum/Folder.svelte"), +}; + +const MEMORY: Blob = Blob { + oid: oid!("b84992d24be67536837f5ab45a943f1b3f501878"), + contents: include_bytes!("platinum/memory.rs"), +}; + +const ARROWS: Blob = Blob { + oid: oid!("95418c04010a3cc758fb3a37f9918465f147566f"), + contents: include_bytes!("platinum/arrows.txt"), +}; + +const EMOJI: Blob = Blob { + oid: oid!("1570277532948712fea9029d100a4208f9e34241"), + contents: include_bytes!("platinum/emoji.txt"), +}; + +const GARDEN: Blob = Blob { + oid: oid!("859f93b3b6a687a961ea7dd54277ae12d93567bf"), + contents: include_bytes!("platinum/garden.txt"), +}; + +pub(super) fn init() -> TempDir { + use git2::FileMode::{Blob as Regular, BlobExecutable as Executable}; + + let dir = tempfile::tempdir().unwrap(); + let repo = Repository::init(dir.path()).unwrap(); + let empty_tree = repo.treebuilder(None).unwrap().write().unwrap(); + let mut tree_oid = empty_tree; + let mut tree = TreeUpdateBuilder::new(); + + let empty = Blob::EMPTY.write(&repo); + let readme_initial = README_1.write(&repo); + let readme_updated = README_2.write(&repo); + let readme_diff_test = README_3.write(&repo); + let license = LICENSE.write(&repo); + let eval_initial = EVAL.write(&repo); + let folder = FOLDER.write(&repo); + let memory = MEMORY.write(&repo); + let arrows = ARROWS.write(&repo); + let emoji = EMOJI.write(&repo); + let garden = GARDEN.write(&repo); + + // The second version of `Eval.hs` used in tests only differs from + // the first version by a difference of 9 bytes inserted. Instead + // of duplicating the file, we compute the second version from the first + // version by splicing 9 bytes. + let eval_updated = { + let mut contents = EVAL.to_vec(); + + const INSERT: &[u8; 9] = b", the MVP"; + + /// The index at which we need to insert [`INSERT`] into [`contents`]. + /// + /// This was computed via a naive linear search: + /// ```no_run + /// const NEEDLE: &[u8; 16] = b", original, eval"; + /// let index = contents + /// .array_windows() + /// .enumerate() + /// .find_map(|(i, window)| (window == NEEDLE).then_some(i)) + /// .unwrap() + /// + NEEDLE.len(); + /// ``` + const INDEX: usize = 623; + + contents.splice(INDEX..INDEX, INSERT.to_vec()); + + let oid = repo.blob(&contents).unwrap(); + assert_eq!( + radicle_oid::Oid::from(oid), + oid!("7d6240123a8d8ea8a8376610168a0a4bcb96afd0") + ); + oid + }; + + let ls = gunzip( + &repo, + oid!("87c2d5149737b266cfe35ca6fa8d2362048613ae"), + include_bytes!("platinum/ls.gz"), + ); + let test = gunzip( + &repo, + oid!("0cced79cda4babfd382621200cb6fdc6470e3c47"), + include_bytes!("platinum/test.gz"), + ); + let cat = gunzip( + &repo, + oid!("0bbb14b0f0d3b6e658879748a720ec601108d26d"), + include_bytes!("platinum/cat.gz"), + ); + + let initial = { + tree.upsert("README.md", readme_initial, Regular); + + let sign = rudolfs(1_575_282_266); + + commit( + &repo, + write_tree(&repo, &mut tree, &mut tree_oid), + &[], + sign.clone(), + sign, + "Initial commit FTW!\n", + Some(include_str!("platinum/signatures/initial.sig")), + oid!("d3464e33d75c75c99bfb90fa2e9d16efc0b7d0e3"), + ) + }; + + for name in [ + "refs/tags/v0.1.0", + "refs/namespaces/golden/refs/tags/v0.1.0", + "refs/namespaces/golden/refs/remotes/kickflip/tags/v0.1.0", + ] { + repo.reference(name, initial.into(), false, "").unwrap(); + } + + let nested = { + tree.upsert( + "this/is/a/really/deeply/nested/directory/tree/.gitkeep", + empty, + Regular, + ); + + let sign = rudolfs(1_575_282_370); + + commit( + &repo, + write_tree(&repo, &mut tree, &mut tree_oid), + &[initial], + sign.clone(), + sign, + "Add fixture for deeply nested directories\n", + Some(include_str!("platinum/signatures/nested.sig")), + oid!("2429f097664f9af0c5b7b389ab998b2199ffa977"), + ) + }; + + for name in [ + "refs/tags/v0.2.0", + "refs/namespaces/golden/refs/tags/v0.2.0", + ] { + repo.reference(name, nested.into(), false, "").unwrap(); + } + + let sources = { + tree.upsert("examples/Eval.hs", eval_initial, Regular); + tree.upsert("examples/Folder.svelte", folder, Regular); + tree.upsert("examples/memory.rs", memory, Regular); + + let sign = rudolfs(1_575_282_874); + + commit( + &repo, + write_tree(&repo, &mut tree, &mut tree_oid), + &[nested], + sign.clone(), + sign, + "Add some source code example files\n", + Some(include_str!("platinum/signatures/sources.sig")), + oid!("f3a089488f4cfd1a240a9c01b3fcc4c34a4e97b2"), + ) + }; + let binaries = { + tree.upsert("bin/cat", cat, Executable); + tree.upsert("bin/ls", ls, Executable); + tree.upsert("bin/test", test, Executable); + + let sign = rudolfs(1_575_282_964); + + commit( + &repo, + write_tree(&repo, &mut tree, &mut tree_oid), + &[sources], + sign.clone(), + sign, + "Add some binary files\n", + Some(include_str!("platinum/signatures/binaries.sig")), + oid!("19bec071db6474af89c866a1bd0e4b1ff76e2b97"), + ) + }; + + repo.reference("refs/tags/v0.3.0", binaries.into(), false, "") + .unwrap(); + + let moved = { + tree.remove("examples/Eval.hs"); + tree.remove("examples/Folder.svelte"); + tree.remove("examples/memory.rs"); + tree.upsert("src/Eval.hs", eval_initial, Regular); + tree.upsert("src/Folder.svelte", folder, Regular); + tree.upsert("src/memory.rs", memory, Regular); + + let sign = rudolfs(1_575_283_266); + + commit( + &repo, + write_tree(&repo, &mut tree, &mut tree_oid), + &[binaries], + sign.clone(), + sign, + "Move examples to \"src\"\n", + Some(include_str!("platinum/signatures/moved.sig")), + oid!("e24124b7538658220b5aaf3b6ef53758f0a106dc"), + ) + }; + + let texts = { + tree.upsert("text/arrows.txt", arrows, Regular); + tree.upsert("text/emoji.txt", emoji, Regular); + tree.upsert("text/garden.txt", garden, Regular); + + let sign = rudolfs(1_575_283_425); + + commit( + &repo, + write_tree(&repo, &mut tree, &mut tree_oid), + &[moved], + sign.clone(), + sign, + "Add text files\n", + Some(include_str!("platinum/signatures/texts.sig")), + oid!("1e0206da8571ca71c51c91154e2fee376e09b4e7"), + ) + }; + + let common = { + tree.upsert(".i-am-well-hidden", empty, Regular); + tree.upsert(".i-too-am-hidden", empty, Regular); + + let sign = rudolfs(1_575_283_503); + + commit( + &repo, + write_tree(&repo, &mut tree, &mut tree_oid), + &[texts], + sign.clone(), + sign, + "Add dotfiles\n", + Some(include_str!("platinum/signatures/common.sig")), + oid!("1820cb07c1a890016ca5578aa652fd4d4c38967e"), + ) + }; + + let common_tree = tree_oid; + let dev = { + tree.upsert("here-we-are-on-a-dev-branch.lol", empty, Regular); + let sign = rudolfs(1_575_283_616); + + commit( + &repo, + write_tree(&repo, &mut tree, &mut tree_oid), + &[common], + sign.clone(), + sign, + "Commit on the dev branch\n", + Some(include_str!("platinum/signatures/dev.sig")), + oid!("27acd68c7504755aa11023300890bb85bbd69d45"), + ) + }; + + for name in [ + "refs/heads/dev", + "refs/namespaces/golden/refs/heads/banana", + "refs/namespaces/golden/refs/namespaces/silver/refs/heads/master", + "refs/namespaces/golden/refs/remotes/kickflip/heads/fakie/bigspin", + "refs/namespaces/golden/refs/remotes/kickflip/heads/heelflip", + "refs/namespaces/me/refs/remotes/fein/heads/feature/#1194", + "refs/remotes/origin/dev", + ] { + repo.reference(name, dev.into(), false, "").unwrap(); + } + + tree_oid = common_tree; + + let deletion_added = { + tree.upsert("test-file-deletion.txt", empty, Regular); + + let sign = rudolfs(1_575_468_360); + + commit( + &repo, + write_tree(&repo, &mut tree, &mut tree_oid), + &[common], + sign.clone(), + sign, + "Add file which will be deleted later\n", + Some(include_str!("platinum/signatures/deletion-added.sig")), + oid!("91b69e00cd8e5a07e20942e9e4457d83ce7a3ff1"), + ) + }; + + repo.reference("refs/tags/v0.4.0", deletion_added.into(), false, "") + .unwrap(); + + let deletion_removed = { + tree.remove("test-file-deletion.txt"); + + let sign = rudolfs(1_575_468_397); + + commit( + &repo, + write_tree(&repo, &mut tree, &mut tree_oid), + &[deletion_added], + sign.clone(), + sign, + "Delete unneeded file\n", + Some(include_str!("platinum/signatures/deletion-removed.sig")), + oid!("80ded66281a4de2889cc07293a8f10947c6d57fe"), + ) + }; + + repo.reference("refs/tags/v0.5.0", deletion_removed.into(), false, "") + .unwrap(); + + let long_message = { + let sign = |author: Author| author.signature(&Time::new(1_576_170_713, 60)); + + commit( + &repo, + write_tree(&repo, &mut tree, &mut tree_oid), + &[deletion_removed], + sign(ALEXANDER), + sign(GITHUB), + "Add a long commit message to commit message body (#1)\n\nIn order to test the correct delivery of the message part of the commit\r\nwe add this commit which has both by expanding beyond the summary.", + Some(include_str!("platinum/signatures/long-message.sig")), + oid!("d6880352fc7fda8f521ae9b7357668b17bb5bad5"), + ) + }; + + { + let target = repo.find_object(long_message.into(), None).unwrap(); + let tagger = THOMAS.signature(&Time::new(1_620_740_737, 120)); + let tag = repo + .tag( + "v0.6.0", + &target, + &tagger, + "An annotated tag message for v0.6.0\n", + false, + ) + .unwrap(); + assert_eq!( + radicle_oid::Oid::from(tag), + oid!("4d1f4af2703074d37cb877f4fdbe36322c8e541d") + ); + } + + let long_message_tree = tree_oid; + let readme = { + tree.upsert("README.md", readme_updated, Regular); + + let sign = |seconds| FINTAN_1.signature(&Time::new(seconds, 0)); + + commit( + &repo, + write_tree(&repo, &mut tree, &mut tree_oid), + &[long_message], + sign(1_584_362_521), + sign(1_584_362_684), + "Updated README with radicle-surf link\n", + None, + oid!("80bacafba303bf0cdf6142921f430ff265f25095"), + ) + }; + tree_oid = long_message_tree; + + let docs = { + tree.upsert("src/Eval.hs", eval_updated, Regular); + + let sign = |author: Author| author.signature(&Time::new(1_578_309_972, 0)); + + commit( + &repo, + write_tree(&repo, &mut tree, &mut tree_oid), + &[long_message], + sign(FINTAN_2), + sign(GITHUB), + "Extend the docs (#2)\n\nI want to have files under src that have separate commits.\r\nThat way src's latest commit isn't the same as all its files, instead it's the file that was touched last.", + Some(include_str!("platinum/signatures/docs.sig")), + oid!("3873745c8f6ffb45c990eb23b491d4b4b6182f95"), + ) + }; + + let folder_removed = { + tree.remove("src/Folder.svelte"); + + let sign = |author: Author| author.signature(&Time::new(1_582_198_877, 60)); + + commit( + &repo, + write_tree(&repo, &mut tree, &mut tree_oid), + &[docs], + sign(RUDOLFS), + sign(GITHUB), + "Remove src/Folder.svelte (#3)\n\nIt was a bad idea to have an actual source file which is used by\r\nradicle-upstream in the fixtures repository. It gets in the way of\r\nlinting and editors pick it up as a regular source file by accident.", + Some(include_str!("platinum/signatures/folder-removed.sig")), + oid!("a57846bbc8ced6587bf8329fc4bce970eb7b757e"), + ) + }; + + let merged = { + tree.upsert("README.md", readme_updated, Regular); + + let sign = |author: Author| author.signature(&Time::new(1_584_367_899, 60)); + + commit( + &repo, + write_tree(&repo, &mut tree, &mut tree_oid), + &[folder_removed, readme], + sign(ALEXANDER), + sign(GITHUB), + "Merge pull request #4 from FintanH/fintan/update-readme-no-sig\n\nUpdated README", + Some(include_str!("platinum/signatures/merged.sig")), + oid!("223aaf87d6ea62eef0014857640fd7c8dd0f80b5"), + ) + }; + + let master = { + for path in [ + "special/-dash-", + "special/...", + "special/:colon:", + "special/;semicolon;", + "special/@at@", + "special/_underscore_", + "special/c++", + "special/faux\\path", + "special/i need some space", + "special/qs?param1=value?param2=value2#hash", + "special/~tilde~", + "special/👹👹👹", + ] { + tree.upsert(path, empty, Regular); + } + + let sign = |author: Author| author.signature(&Time::new(1_602_778_504, 120)); + + commit( + &repo, + write_tree(&repo, &mut tree, &mut tree_oid), + &[merged], + sign(RUDOLFS), + sign(GITHUB), + "Add files with special characters in their filenames (#5)\n\n", + Some(include_str!("platinum/signatures/master.sig")), + oid!("a0dd9122d33dff2a35f564d564db127152c88e02"), + ) + }; + + for name in [ + "refs/heads/master", + "refs/namespaces/golden/refs/heads/master", + "refs/namespaces/me/refs/heads/feature/#1194", + "refs/remotes/banana/orange/pineapple", + "refs/remotes/banana/pineapple", + "refs/remotes/origin/master", + ] { + repo.reference(name, master.into(), false, "").unwrap(); + } + + let master_tree = tree_oid; + tree_oid = empty_tree; + + let empty_branch = { + let sign = han(1_674_618_111); + let removed_all = commit( + &repo, + write_tree(&repo, &mut tree, &mut tree_oid), + &[master], + sign.clone(), + sign, + "remove all files\n", + None, + oid!("13a866a47591625c3fb7895e454369cd5874badc"), + ); + + let sign = han(1_674_618_130); + commit( + &repo, + write_tree(&repo, &mut tree, &mut tree_oid), + &[removed_all], + sign.clone(), + sign, + "an empty commit.\n", + None, + oid!("e972683fe8136bf8a5cb2378cf50303554008049"), + ) + }; + + for name in [ + "refs/heads/empty-branch", + "refs/remotes/origin/empty-branch", + ] { + repo.reference(name, empty_branch.into(), false, "") + .unwrap(); + } + + let diff_test = { + tree_oid = master_tree; + tree.upsert("LICENSE", license, Regular); + tree.upsert("README.md", readme_diff_test, Regular); + tree.remove("text/emoji.txt"); + tree.upsert("emoji.txt", emoji, Regular); + tree.upsert("file_operations/copied.md", readme_updated, Regular); + tree.remove("text/arrows.txt"); + + commit( + &repo, + write_tree(&repo, &mut tree, &mut tree_oid), + &[master], + han(1_675_087_389), + SEBASTIAN.signature(&Time::new(1_687_938_471, 120)), + "One commit to include add, delete, modify, copy and move\n\nFor copies detection, we copy the README file which is also being\nmodified in the same changeset.\nDue to unmodified copies detection being to expensive.\n", + Some(include_str!("platinum/signatures/diff-test.sig")), + oid!("29b78a041bffb955b597719b27c51134a49555c1"), + ) + }; + + for name in ["refs/heads/diff-test", "refs/remotes/origin/diff-test"] { + repo.reference(name, diff_test.into(), false, "").unwrap(); + } + + repo.reference_symbolic( + "refs/remotes/origin/HEAD", + "refs/remotes/origin/master", + false, + "create platinum fixture", + ) + .unwrap(); + + repo.set_head("refs/heads/dev").unwrap(); + + dir +} + +fn gunzip(repo: &Repository, expected: radicle_oid::Oid, bytes: &[u8]) -> Oid { + let mut decoded = Vec::new(); + GzDecoder::new(bytes).read_to_end(&mut decoded).unwrap(); + let oid = repo.blob(&decoded).unwrap(); + assert_eq!(radicle_oid::Oid::from(oid), expected); + oid +} + +fn write_tree( + repo: &Repository, + builder: &mut TreeUpdateBuilder, + baseline: &mut Oid, +) -> radicle_oid::Oid { + let tree = repo.find_tree(*baseline).unwrap(); + *baseline = mem::take(builder).create_updated(repo, &tree).unwrap(); + (*baseline).into() +} + +#[allow(clippy::too_many_arguments)] +fn commit( + repo: &Repository, + tree: radicle_oid::Oid, + parents: &[radicle_oid::Oid], + author: Signature<'_>, + committer: Signature<'_>, + message: &str, + signature: Option<&str>, + expected: radicle_oid::Oid, +) -> radicle_oid::Oid { + let tree = repo.find_tree(tree.into()).unwrap(); + let parents = parents + .iter() + .map(|oid| repo.find_commit(oid.into()).unwrap()) + .collect::>(); + let parent_refs = parents.iter().collect::>(); + + let oid = match signature { + Some(signature) => { + let buffer = repo + .commit_create_buffer(&author, &committer, message, &tree, &parent_refs) + .unwrap(); + let content = str::from_utf8(&buffer).unwrap(); + repo.commit_signed(content, signature, None).unwrap() + } + None => repo + .commit(None, &author, &committer, message, &tree, &parent_refs) + .unwrap(), + }; + + let oid = oid.into(); + assert_eq!(oid, expected); + oid +} diff --git a/crates/radicle-surf/src/test/platinum/Eval.hs b/crates/radicle-surf/src/test/platinum/Eval.hs new file mode 100644 index 000000000..8c7447d13 --- /dev/null +++ b/crates/radicle-surf/src/test/platinum/Eval.hs @@ -0,0 +1,253 @@ +module Radicle.Lang.Eval + ( eval + , baseEval + , callFn + , ($$) + , createModule + ) where + +import Protolude hiding (Constructor, Handle, TypeError, (<>)) + +import qualified Data.List.NonEmpty as NonEmpty +import qualified Data.Map as Map +import Data.Semigroup ((<>)) +import qualified Data.Sequence as Seq +import qualified Data.Set as Set +import qualified GHC.Exts as GhcExts + +import Radicle.Lang.Core +import qualified Radicle.Lang.Doc as Doc +import Radicle.Lang.Identifier (Ident(..)) +import Radicle.Lang.Internal.Orphans () + +-- | The built-in, original, eval. +baseEval :: Monad m => Value -> Lang m Value +baseEval val = logValPos val $ case val of + Atom i -> lookupAtom i + List (f:vs) -> f $$ vs + List xs -> throwErrorHere + $ WrongNumberOfArgs ("application: " <> show xs) + 2 + (length xs) + Vec xs -> Vec <$> traverse baseEval xs + Dict mp -> do + let evalBoth (a,b) = (,) <$> baseEval a <*> baseEval b + kvs <- traverse evalBoth (Map.toList mp) + dict $ Map.fromList kvs + autoquote -> pure autoquote + + +-- | The buck-passing eval. Uses whatever 'eval' is in scope. +eval :: Monad m => Value -> Lang m Value +eval val = do + e <- lookupAtom (Ident "eval") + logValPos e $ do + st <- gets bindingsToRadicle + result <- callFn e [val, st] + case result of + List [val', newSt] -> do + setBindings newSt + pure val' + _ -> throwErrorHere + $ OtherError "eval: should return list with value and new env" + + + +specialForms :: forall m. (Monad m) => Map Ident ([Value] -> Lang m Value) +specialForms = Map.fromList $ first Ident <$> + [ ( "fn" + , \case + args : b : bs -> do + e <- gets bindingsEnv + let toLambda argNames = pure (Lambda argNames (b :| bs) e) + case args of + Vec atoms_ -> do + atoms <- traverse isAtom (toList atoms_) ?? toLangError (SpecialForm "fn" "One of the arguments was not an atom") + toLambda (PosArgs atoms) + Atom name -> do + toLambda (VarArgs name) + _ -> throwErrorHere $ SpecialForm "fn" "Function parameters must be one atom or a vector of atoms" + _ -> throwErrorHere $ SpecialForm "fn" "Function needs parameters (one atom or a vector of atoms) and a body" + ) + , ( "module", createModule ) + , ("quote", \case + [v] -> pure v + xs -> throwErrorHere $ WrongNumberOfArgs "quote" 1 (length xs)) + , ("def", \case + [Atom name, val] -> def name Nothing val + [_, _] -> throwErrorHere $ OtherError "def expects atom for first arg" + [Atom name, String d, val] -> def name (Just d) val + xs -> throwErrorHere $ WrongNumberOfArgs "def" 2 (length xs)) + , ( "def-rec" + , \case + [Atom name, val] -> defRec name Nothing val + [_, _] -> throwErrorHere $ OtherError "def-rec expects atom for first arg" + [Atom name, String d, val] -> defRec name (Just d) val + xs -> throwErrorHere $ WrongNumberOfArgs "def-rec" 2 (length xs) + ) + , ("do", (lastDef nil <$>) . traverse baseEval) + , ("catch", \case + [l, form, handler] -> do + mlabel <- baseEval l + s <- get + case mlabel of + -- TODO reify stack + Atom label -> baseEval form `catchError` \err@(LangError _stack e) -> do + (thrownLabel, thrownValue) <- errorDataToValue e + if thrownLabel == label || label == Ident "any" + then do + put s + handlerclo <- baseEval handler + callFn handlerclo [thrownValue] + else throwError err + _ -> throwErrorHere $ SpecialForm "catch" "first argument must be atom" + xs -> throwErrorHere $ WrongNumberOfArgs "catch" 3 (length xs)) + , ("if", \case + [condition, t, f] -> do + b <- baseEval condition + -- I hate this as much as everyone that might ever read Haskell, but + -- in Lisps a lot of things that one might object to are True... + if b == Boolean False then baseEval f else baseEval t + xs -> throwErrorHere $ WrongNumberOfArgs "if" 3 (length xs)) + , ( "cond", (cond =<<) . evenArgs "cond" ) + , ( "match", match ) + ] + where + cond = \case + [] -> pure nil + (c,e):ps -> do + b <- baseEval c + if b /= Boolean False + then baseEval e + else cond ps + + match = \case + v : cases -> do + cs <- evenArgs "match" cases + v' <- baseEval v + goMatches v' cs + _ -> throwErrorHere $ PatternMatchError NoValue + + goMatches _ [] = throwErrorHere (PatternMatchError NoMatch) + goMatches v ((m, body):cases) = do + patFn <- baseEval m + matchPat <- lookupAtom (Ident "match-pat") + res <- callFn matchPat [patFn, v] + let res_ = fromRad res + case res_ of + Right (Just (Dict binds)) -> do + b <- bindsToEnv m binds + addBinds b *> baseEval body + Right Nothing -> goMatches v cases + _ -> throwErrorHere $ PatternMatchError (BadBindings m) + + bindsToEnv pat m = do + is <- traverse isBind (Map.toList m) + pure $ Env (Map.fromList is) + where + isBind (Atom x, v) = pure (x, Doc.Docd Nothing v) + isBind _ = throwErrorHere $ PatternMatchError (BadBindings pat) + + addBinds e = modify (\s -> s { bindingsEnv = e <> bindingsEnv s }) + + def name doc_ val = do + val' <- baseEval val + defineAtom name doc_ val' + pure nil + + defRec name doc_ val = do + val' <- baseEval val + case val' of + Lambda is b e -> do + defineAtom name doc_ $ LambdaRec name is b e + pure nil + LambdaRec{} -> throwErrorHere $ + OtherError "'def-rec' cannot be used to alias functions. Use 'def' instead" + _ -> throwErrorHere $ OtherError "'def-rec' can only be used to define functions" + +data ModuleMeta = ModuleMeta + { name :: Ident + , exports :: [Ident] + , doc :: Text + } + +-- | Given a list of forms, the first of which should be module declaration, +-- runs the rest of the forms in a new scope, and then defs the module value +-- according to the name in the declaration. +createModule :: forall m. Monad m => [Value] -> Lang m Value +createModule = \case + (m : forms) -> do + m' <- baseEval m >>= meta + e <- withEnv identity $ traverse_ eval forms *> gets bindingsEnv + let exportsSet = Set.fromList (exports m') + let undefinedExports = Set.difference exportsSet (Map.keysSet (fromEnv e)) + env <- if null undefinedExports + then pure . VEnv . Env $ Map.restrictKeys (fromEnv e) exportsSet + else throwErrorHere (ModuleError (UndefinedExports (name m') (Set.toList undefinedExports))) + let modu = Dict $ Map.fromList + [ (Keyword (Ident "module"), Atom (name m')) + , (Keyword (Ident "env"), env) + , (Keyword (Ident "exports"), Vec (Seq.fromList (Atom <$> exports m'))) + ] + defineAtom (name m') (Just (doc m')) modu + pure modu + _ -> throwErrorHere (ModuleError MissingDeclaration) + where + meta v@(Dict d) = do + name <- modLookup v "module" d "missing `:module` key" + doc <- modLookup v "doc" d "missing `:doc` key" + exports <- modLookup v "exports" d "Missing `:exports` key" + case (name, doc, exports) of + (Atom n, String ds, Vec es) -> do + is <- traverse isAtom es ?? toLangError (ModuleError (InvalidDeclaration "`:exports` must be a vector of atoms" v)) + pure $ ModuleMeta n (toList is) ds + _ -> throwErrorHere (ModuleError (InvalidDeclaration "`:module` must be an atom, `:doc` must be a string and `:exports` must be a vector" v)) + meta v = throwErrorHere (ModuleError (InvalidDeclaration "must be dict" v)) + modLookup v k d e = kwLookup k d ?? toLangError (ModuleError (InvalidDeclaration e v)) + + +-- | Call a lambda or primitive function @f@ with @arguments@. @f@ and +-- @argumenst@ are not evaluated. +callFn :: forall m. Monad m => Value -> [Value] -> Lang m Value +callFn f arguments = case f of + Lambda argNames body closure -> do + args <- argumentBindings argNames + evalManyWithEnv (args <> closure) body + LambdaRec self argNames body closure -> do + args <- argumentBindings argNames + let selfBinding = GhcExts.fromList (Doc.noDocs [(self, f)]) + evalManyWithEnv (args <> selfBinding <> closure) body + PrimFn i -> do + fn <- lookupPrimop i + fn arguments + _ -> throwErrorHere $ NonFunctionCalled f + where + evalManyWithEnv :: Env Value -> NonEmpty Value -> Lang m Value + evalManyWithEnv env exprs = + NonEmpty.last <$> withEnv (const env) (traverse baseEval exprs) + argumentBindings :: LambdaArgs -> Lang m (Env Value) + argumentBindings argNames = case argNames of + PosArgs names -> + if length names /= length arguments + then throwErrorHere $ WrongNumberOfArgs "lambda" (length names) (length arguments) + else toArgs $ zip names arguments + VarArgs name -> + toArgs [(name, Vec $ Seq.fromList arguments)] + where toArgs = pure . GhcExts.fromList . Doc.noDocs + +-- | Process special forms or call function. If @f@ is an atom that +-- indicates a special form that special form is processed. Otherwise +-- @f@ and @vs@ are evaluated in 'callFn' is called. +infixr 1 $$ +($$) :: Monad m => Value -> [Value] -> Lang m Value +f $$ vs = case f of + Atom i -> + case Map.lookup i specialForms of + Just form -> form vs + Nothing -> fnApp + _ -> fnApp + where + fnApp = do + f' <- baseEval f + vs' <- traverse baseEval vs + callFn f' vs' diff --git a/crates/radicle-surf/src/test/platinum/Folder.svelte b/crates/radicle-surf/src/test/platinum/Folder.svelte new file mode 100644 index 000000000..a50cdb374 --- /dev/null +++ b/crates/radicle-surf/src/test/platinum/Folder.svelte @@ -0,0 +1,99 @@ + + + + +{#await $sourceTree then result} +
+ {#if !firstEntry} + + {/if} + + {#if expanded || firstEntry} + {#each result.data.tree.entries as entry} + {#if entry.info.objectType === TREE} + + {:else} + + {/if} + {/each} + {/if} +
+{/await} diff --git a/crates/radicle-surf/src/test/platinum/LICENSE b/crates/radicle-surf/src/test/platinum/LICENSE new file mode 100644 index 000000000..02f70f56e --- /dev/null +++ b/crates/radicle-surf/src/test/platinum/LICENSE @@ -0,0 +1,2 @@ +This is a license file. + diff --git a/crates/radicle-surf/src/test/platinum/arrows.txt b/crates/radicle-surf/src/test/platinum/arrows.txt new file mode 100644 index 000000000..95418c040 --- /dev/null +++ b/crates/radicle-surf/src/test/platinum/arrows.txt @@ -0,0 +1,7 @@ + ;;;;; ;;;;; ;;;;; + ;;;;; ;;;;; ;;;;; + ;;;;; ;;;;; ;;;;; + ;;;;; ;;;;; ;;;;; +..;;;;;.. ..;;;;;.. ..;;;;;.. + ':::::' ':::::' ':::::' + ':` ':` ':` diff --git a/crates/radicle-surf/src/test/platinum/cat.gz b/crates/radicle-surf/src/test/platinum/cat.gz new file mode 100644 index 000000000..d3e231557 Binary files /dev/null and b/crates/radicle-surf/src/test/platinum/cat.gz differ diff --git a/crates/radicle-surf/src/test/platinum/emoji.txt b/crates/radicle-surf/src/test/platinum/emoji.txt new file mode 100644 index 000000000..157027753 --- /dev/null +++ b/crates/radicle-surf/src/test/platinum/emoji.txt @@ -0,0 +1,8 @@ + 🌞 + ☁ + ____🐓_ +---| |--------- + / \ 🌵 + + ~~ + 🐍 ~~ diff --git a/crates/radicle-surf/src/test/platinum/garden.txt b/crates/radicle-surf/src/test/platinum/garden.txt new file mode 100644 index 000000000..859f93b3b --- /dev/null +++ b/crates/radicle-surf/src/test/platinum/garden.txt @@ -0,0 +1,8 @@ + _(_)_ wWWWw _ + @@@@ (_)@(_) vVVVv _ @@@@ (___) _(_)_ + @@()@@ wWWWw (_)\ (___) _(_)_ @@()@@ Y (_)@(_) + @@@@ (___) `|/ Y (_)@(_) @@@@ \|/ (_)\ + / Y \| \|/ /(_) \| |/ | + \ | \ |/ | / \ | / \|/ |/ \| \|/ +jgs \\|// \\|/// \\\|//\\\|/// \|/// \\\|// \\|// \\\|// +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/radicle-surf/src/test/platinum/ls.gz b/crates/radicle-surf/src/test/platinum/ls.gz new file mode 100644 index 000000000..03bb245f0 Binary files /dev/null and b/crates/radicle-surf/src/test/platinum/ls.gz differ diff --git a/crates/radicle-surf/src/test/platinum/memory.rs b/crates/radicle-surf/src/test/platinum/memory.rs new file mode 100644 index 000000000..b84992d24 --- /dev/null +++ b/crates/radicle-surf/src/test/platinum/memory.rs @@ -0,0 +1,172 @@ +//! Provides [MemoryClient] to run the registry ledger in memory. + +use futures01::{future, prelude::*}; +use std::sync::{Arc, Mutex}; + +use paint_support::storage::generator::{StorageMap, StorageValue}; +use parity_scale_codec::{Decode, FullCodec}; +use sr_primitives::{traits::Hash as _, BuildStorage as _}; + +use radicle_registry_runtime::{ + balances, registry, BalancesConfig, Executive, GenesisConfig, Hash, Hashing, Runtime, +}; + +use crate::interface::*; + +/// [Client] implementation using native runtime code and in memory state through +/// [sr_io::TestExternalities]. +/// +/// # Differences with real [Client] +/// +/// The [MemoryClient] does not produce blocks. In particular the `blocks` field in +/// [TransactionApplied]` always equals `Hash::default` when returned from [Client::submit]. +/// +/// The responses returned from the client never result in an [Error]. +#[derive(Clone)] +pub struct MemoryClient { + test_ext: Arc>, + genesis_hash: Hash, +} + +impl MemoryClient { + pub fn new() -> Self { + let genesis_config = GenesisConfig { + paint_aura: None, + paint_balances: Some(BalancesConfig { + balances: vec![( + ed25519::Pair::from_string("//Alice", None) + .unwrap() + .public(), + 1 << 60, + )], + vesting: vec![], + }), + paint_sudo: None, + system: None, + }; + let mut test_ext = sr_io::TestExternalities::new(genesis_config.build_storage().unwrap()); + let genesis_hash = test_ext.execute_with(|| { + paint_system::Module::::initialize( + &1, + &[0u8; 32].into(), + &[0u8; 32].into(), + &Default::default(), + ); + paint_system::Module::::block_hash(0) + }); + MemoryClient { + test_ext: Arc::new(Mutex::new(test_ext)), + genesis_hash, + } + } + + pub fn fetch_value, Value: FullCodec>(&self) -> Response + where + S::Query: Send + 'static, + { + let test_ext = &mut self.test_ext.lock().unwrap(); + let result = storage_lookup(test_ext, S::storage_value_final_key()); + Box::new( + result + .map(S::from_optional_value_to_query) + .map_err(Error::Codec) + .into_future(), + ) + } + + pub fn fetch_map_value, Key: FullCodec, Value: FullCodec>( + &self, + key: Key, + ) -> Response + where + S::Query: Send + 'static, + { + let test_ext = &mut self.test_ext.lock().unwrap(); + let result = storage_lookup(test_ext, S::storage_map_final_key(key)); + Box::new( + result + .map(S::from_optional_value_to_query) + .map_err(Error::Codec) + .into_future(), + ) + } +} + +impl Client for MemoryClient { + fn submit( + &self, + author: &ed25519::Pair, + call: Call_, + ) -> Response, Error> { + let account_id = author.public(); + let client = self.clone(); + let key_pair = author.clone(); + Box::new( + self.get_transaction_extra(&account_id) + .and_then(move |extra| { + let extrinsic = crate::extrinsic::signed_extrinsic( + &key_pair, + call.into_runtime_call(), + extra.nonce, + extra.genesis_hash, + ); + let tx_hash = Hashing::hash_of(&extrinsic); + let test_ext = &mut client.test_ext.lock().unwrap(); + let events = test_ext.execute_with(move || { + let event_start_index = paint_system::Module::::event_count(); + let _apply_outcome = Executive::apply_extrinsic(extrinsic).unwrap(); + paint_system::Module::::events() + .into_iter() + .skip(event_start_index as usize) + .map(|event_record| event_record.event) + .collect::>() + }); + let result = Call_::result_from_events(events.clone())?; + Ok(TransactionApplied { + tx_hash, + block: Default::default(), + events, + result, + }) + }), + ) + } + + fn get_transaction_extra(&self, account_id: &AccountId) -> Response { + let test_ext = &mut self.test_ext.lock().unwrap(); + let nonce = + test_ext.execute_with(|| paint_system::Module::::account_nonce(account_id)); + Box::new(future::ok(TransactionExtra { + nonce, + genesis_hash: self.genesis_hash, + })) + } + + fn free_balance(&self, account_id: &AccountId) -> Response { + Box::new(self.fetch_map_value::, _, _>(account_id.clone())) + } + + fn get_project(&self, id: ProjectId) -> Response, Error> { + Box::new(self.fetch_map_value::(id)) + } + + fn list_projects(&self) -> Response, Error> { + Box::new(self.fetch_value::()) + } + + fn get_checkpoint(&self, id: CheckpointId) -> Response, Error> { + Box::new(self.fetch_map_value::(id)) + } +} + +/// Lookup and decode a storage value in the [TestExternalities] context. +fn storage_lookup( + test_ext: &mut sr_io::TestExternalities, + key: impl AsRef<[u8]>, +) -> Result, parity_scale_codec::Error> { + let maybe_data = test_ext.execute_with(|| sr_io::storage::get(key.as_ref())); + match maybe_data { + Some(data) => Value::decode(&mut data.as_slice()).map(Some), + None => Ok(None), + } +} diff --git a/crates/radicle-surf/src/test/platinum/signatures/binaries.sig b/crates/radicle-surf/src/test/platinum/signatures/binaries.sig new file mode 100644 index 000000000..83aab0de9 --- /dev/null +++ b/crates/radicle-surf/src/test/platinum/signatures/binaries.sig @@ -0,0 +1,16 @@ +-----BEGIN PGP SIGNATURE----- + +iQIzBAABCAAdFiEEime/6MCYr8AgSm0yaDIsu74NAroFAl3k6RoACgkQaDIsu74N +Arre+RAAwTEQgVJWhU9OCNTUCOjgbs51NlAALyhLNSWENdJ/zNqWHk4XwX8YEsPU +fKtzjwqFzImBSYOz4rje1s0xcqCM+MGaonaCb8bHl2G5lq/rf1LRplVQvFf6WhTR +UxZSOtXKc702m3iWLsOQq45DDd//EoHLse7ISbhh0kh4+p55//PGpm23LllVzpY0 +UuGD7dCFFgHuE+p4gDMSMrwV+AgukjfMHam3wwQePrZzjgG8yO0Z04a87X+CcHUT +zYVw0G3M8aJ26D72ZsA6oYia/cSCJG7kY61iih6TEm13Y2R2UGxRqOvsdNlm5Bpw ++kFOvvuKTs1y0FsQ8Zipe6BqVyxF45+ybEvgLM4cSB9iW0+g1sxKM5PmEmTFlpeW +mwAJ7wVlpH+FwMY+m+lX47BPXo7E1SYzUNfR+8zjm8QlZci05s5Lo0cIKrIAulHN +YLf6YpzKgRp5p+Fhp75jrMCGvZ/7jlX6shhoUe5Y17N2X8TMUHAys/qSN88Qslu2 +LeuQ7eG6eSAgNaTwekBMVSM1yTHZwXbGa1/Vj9zWEu6BgM9U2zeryz9ATTARY+/Y +nzSVYajtPwZLEEo8LUdAWF6P919/wdfPdB/6AaYu0eFiy8jr1a4RN4I3mZjZP76w ++sziMIWMKg63CPvyYA0dqul3u4fWZ2ymiFjwNunEp8MQ2oVSH80= +=1/L7 +-----END PGP SIGNATURE----- \ No newline at end of file diff --git a/crates/radicle-surf/src/test/platinum/signatures/common.sig b/crates/radicle-surf/src/test/platinum/signatures/common.sig new file mode 100644 index 000000000..05f171026 --- /dev/null +++ b/crates/radicle-surf/src/test/platinum/signatures/common.sig @@ -0,0 +1,16 @@ +-----BEGIN PGP SIGNATURE----- + +iQIzBAABCAAdFiEEime/6MCYr8AgSm0yaDIsu74NAroFAl3k6zYACgkQaDIsu74N +ArrZ5hAAwjx6uL0hhTeZ/w6zGocS9I1DeQAJVMFQVeqVBi3Z4+H0TEY14qEexDVn +U3k6RvfRE1TcyXYtO7SzPKCqcLuXpZWjSfXuxjFDRVObEFrfSqKx2Wc89Nxn0xb1 +ltO89TNmchYPTzqEGhYUAsxp7ff/piIYzc6GG5DOuy8vggQzujpEA5ujg3iKXILQ +3K2dXMBEnEqf5S9SHDcTVCTXqcrNA2kjW2TiiYkxFFJoqwNjpxj22yRfAGt/2Jq5 +srjZVxW50UK9zLhsiYEcy49Md98NcG9if0QKitKVpo6GpyM1qqKFJsXZbroAzf6R +U7PZwfY24DqN9lveYQomnUTNkRxwBgR3di4Z0YNROhyLcjfkzbGMU8v4SYBfv5fG +SQThyo6HMCJLZnTe+7yzNXncpHVaiEn5s4SH98W6thRtZgs2QKbwcM15ZG01XUrD +0cEvGQv+H8J+q9Pt3UnuL6i39iLcfWXHtXRtObV1st6inGbuykxa8lSBpfTAaWYu +Hdqzh3gOnXsKXhwGpgyxPqoUBGM5uyxMYfz1fXba0NUEl3efGN5gZskrl5Wjvx5/ +B7W2D1A+KiRwUHABN9BAORUH5sJLmcaFIyd2c2NXC6DCO7QAlLRcuir6kfS0mnJw +KuyDD7Aron+ZTDUgcRWnSfc1GuCKnI9ToCk3kgW8l/uU8FXow6g= +=0Guy +-----END PGP SIGNATURE----- \ No newline at end of file diff --git a/crates/radicle-surf/src/test/platinum/signatures/deletion-added.sig b/crates/radicle-surf/src/test/platinum/signatures/deletion-added.sig new file mode 100644 index 000000000..5de0cd35b --- /dev/null +++ b/crates/radicle-surf/src/test/platinum/signatures/deletion-added.sig @@ -0,0 +1,16 @@ +-----BEGIN PGP SIGNATURE----- + +iQIzBAABCAAdFiEEime/6MCYr8AgSm0yaDIsu74NAroFAl3nvVUACgkQaDIsu74N +Arrmcg//fulK6vqrAQiZSLmh0qf4Vvm8NLp18k0JYkrT+QbEltwpNSL1U8Z5uO+X +QDtZoCgWN+OhypvihJahhk/QSeD6Zs8RqeR0j91nlgh88t4NEx2K3oU89J4bok1I +TK/7OJgZiSfSQrHPJEC/wZJsGzxG606HgV8yY3maKo958V+/g3ttThzVqk4neVzS +Qb7nWX+/Be3mg2612JDjYmVvzce8q+44B6HWHhjwSkvDx6sB2T8wc2mabnU9TEMJ +jYtmJRUCWWd09mMOLoUQgGlwG/2jwD6b8x2Sx4nEOydVewk89Dem7Vc5WE1ot8ae +q1EIIELxubmXzHotepHlszgstHqjAEOouqnx/Wn5hWdo7uKfUlALkbJc1LyG8Sw+ +y69CbIX0H3w0G3L0+YHdkXbiCwl3EK5aWKaoIHA3DTIs11rmpWvkvncYs8krRkrm +4b2HTVCM7+f5SGqaTz3kTeaTwPfAYQPwvXNMrAVGIO9FYgSSSXuBrxxgQ13LYbvW +pvtlhhZ/TzFsagVVl4Za51dnt+hT0v9fgG9XRey7gGbsWFQwOz12NnlccvDJ4HSg +qAKq3qtQS3GKzAUFcxAczBcxbt0Tx+3VM7gEQKAnzVp3FpXGbYwaxx18lFMqGIJ8 +OzhjMPZDzuZ/SShui3xpuyd+lVn1a83rQ4/9W5BgBxIWhdgNOz4= +=44E7 +-----END PGP SIGNATURE----- \ No newline at end of file diff --git a/crates/radicle-surf/src/test/platinum/signatures/deletion-removed.sig b/crates/radicle-surf/src/test/platinum/signatures/deletion-removed.sig new file mode 100644 index 000000000..73f9fe573 --- /dev/null +++ b/crates/radicle-surf/src/test/platinum/signatures/deletion-removed.sig @@ -0,0 +1,16 @@ +-----BEGIN PGP SIGNATURE----- + +iQIzBAABCAAdFiEEime/6MCYr8AgSm0yaDIsu74NAroFAl3nvXQACgkQaDIsu74N +ArqZvg/9Fp5mxNqyb5nwsTDixSfF4yXDE4R+vGKCids+sxnETepS4Ssnwl2Do/hN +RTItTU09ZE0jXZKoc7qZI/n0b36kca0kfowvmAomgQLqh0yaSb7wkZcDivAvjs5Q +iHfopvLNeI6OG8STVrVx4W8+6TNmq0jlet782rHDZVWpig8UrpbZ59q7yaIC3BDu +2QB9NWj2IJFKJOxCABd0IY71zeH9xYlbcRXwU/8isipjIlTLfdBpaSxTbUjj5Eum +M3EmvGVncDToD4wXijMIKT7qPeVkwfBiZb3RuFgqgI/cOentjKD9xBUuCvGyLSF3 +M5l2Olx0ufAhUaN5IYwkh7fyYB2tUMTBE4Xtamst0HiiKaUoda6UTRMJIF6DZVbP ++Sq4GGcRDuZypCNMLx6gkvrx7rFL3Dzkq/6kcixEqQ8Bq5NOBlCPDg372ERQnU9c +0BCVPI1uIuZf6bwWwUBYuzP09aNJeYtbymTKe2r33VNziANkA7r48mM2g7xA6X1B +SzZTNMHbfqK8ibYZhAfGNI0fbiSXRlmwOpVXEglpXMMZjDWJzyINyXtHrJYdqmSR +ZzFwlCKY4HVrDhsCP+OflQuMbGXdzBQGFs/ksIwOvFsdtgqM2k8ioZMOTE8mBCT4 +9ZfUvnAF3X+opRDIrf+VhESgeck+ZQoNhr2K0WRB605X8W3mN8Y= +=+2J4 +-----END PGP SIGNATURE----- \ No newline at end of file diff --git a/crates/radicle-surf/src/test/platinum/signatures/dev.sig b/crates/radicle-surf/src/test/platinum/signatures/dev.sig new file mode 100644 index 000000000..b8cb8aa04 --- /dev/null +++ b/crates/radicle-surf/src/test/platinum/signatures/dev.sig @@ -0,0 +1,16 @@ +-----BEGIN PGP SIGNATURE----- + +iQIzBAABCAAdFiEEime/6MCYr8AgSm0yaDIsu74NAroFAl3k67AACgkQaDIsu74N +ArrDVw//c85BqWoryW0sqoze5+RRC2pLiKknQgI7x0kue91kJVZ/bSYhePKwuxyM +6lgRScZp7gEyT9AyOZWr7Fyrd+V53dIrYQMW48FlSt5KdqPq3tOclxOzmURxsy9p +Okpv909VesYb8WNyLOBVbHE69su/gh0qYEn1X9kfm1c3dYiAG3s3JuzqRjtSFWV2 +G/KFDl4csflrsbs+iGzfBPwqsIPRk476LdR6gaR17kdy41CnluAksuJZ8Uw4YsGv +tIvsyT08wDd3GqyHrzZ1rcMCh9DlD/ERGeylA2URNmQE/cxttBV+lHjCpF7GZiH1 +UkGA5ln/oHQtw1U7Tye5NDCGOS43tUiy7yWBX5v9S/w1PuCHf8F0ejXGmFqGEOyd +ZSNywhg+p9VJV9/UD1pm1s14DuRJzKhbrja22qVhg9qZJxTm1GWfnRC8met4/BjN +Qyffo4fd9JPmrfYAtY2tEh+VS3S9BAMmhVk6D0thB5DAOAd4M+MIzm5j5ZDJIs2c +w0xqiLH/Ic4XYvvG1egKSMUWjexgwQj/ja9jIGr4UhDKmEz3cbZVw7WJBfiYfdGN +PqgvgW8KHDv4FZIZUu8IuLaB6wPdg/9MSLaNkbpq0/JhNtovqsrLva8OQJPLZVyM +kXz/AXSc9jL03NtpwtCTGV6be4taeoyhcLoSMGrY8APJiJ2n25A= +=VCJq +-----END PGP SIGNATURE----- \ No newline at end of file diff --git a/crates/radicle-surf/src/test/platinum/signatures/diff-test.sig b/crates/radicle-surf/src/test/platinum/signatures/diff-test.sig new file mode 100644 index 000000000..95d84f99a --- /dev/null +++ b/crates/radicle-surf/src/test/platinum/signatures/diff-test.sig @@ -0,0 +1,6 @@ +-----BEGIN SSH SIGNATURE----- +U1NIU0lHAAAAAQAAADMAAAALc3NoLWVkMjU1MTkAAAAgXD7AI9lSHw6d2GBq8kxJmW6itW +/MmPPbY8fzVeuS8i4AAAADZ2l0AAAAAAAAAAZzaGE1MTIAAABTAAAAC3NzaC1lZDI1NTE5 +AAAAQFVcxAVjTRp3x0mYSjcBb10Ywjb+UyZ9Zi8GTofzTeVL+W/2D422qKCsPkbVgQOuaG +OxKsKBwrSBTSOEf8RWKAg= +-----END SSH SIGNATURE----- \ No newline at end of file diff --git a/crates/radicle-surf/src/test/platinum/signatures/docs.sig b/crates/radicle-surf/src/test/platinum/signatures/docs.sig new file mode 100644 index 000000000..195912c53 --- /dev/null +++ b/crates/radicle-surf/src/test/platinum/signatures/docs.sig @@ -0,0 +1,10 @@ +-----BEGIN PGP SIGNATURE----- + +wsBcBAABCAAQBQJeExlUCRBK7hj4Ov3rIwAAdHIIAHnXU+wVSLDL4EQQHxQtWVJA +qCRGExLRqqfXZNWgTpNbYXy7eK1TcqshZFUvUY9uy/AIwjnIMeBz4CbQuB5+2Te4 +RhK7hFtiPjSMhmpIpvL9izsKZCJzIMtx4f7CC8PWsa61mfgy7mnt5td5X42PyhJs +xlkcBWSAGgCH8FfEV1FOAUFQQzztv4VwwvY8myYRLCnjBRghnV7iQsXXqNSmB+Mo +E/vZ6hdt/ylhOs5Bpy9ft4NlArJl8gTsfJrs2RMtybbU+DRFMJAazcSkqM1dhfo+ +hvjIeF758OB7OBftcrpG6JVDNajvkIokxbU//Mz/6OOgktBA8vwaw6NXSgmcYa8= +=qH1p +-----END PGP SIGNATURE----- diff --git a/crates/radicle-surf/src/test/platinum/signatures/folder-removed.sig b/crates/radicle-surf/src/test/platinum/signatures/folder-removed.sig new file mode 100644 index 000000000..f08e2e04f --- /dev/null +++ b/crates/radicle-surf/src/test/platinum/signatures/folder-removed.sig @@ -0,0 +1,10 @@ +-----BEGIN PGP SIGNATURE----- + +wsBcBAABCAAQBQJeTnBdCRBK7hj4Ov3rIwAAdHIIAFedCAtnlo8BtZGRyBpTf975 +Ne7jNqzzA52YPTcZpp4hV+ccO9igHUCyeHlIV79puKbFa353Kq7VKqUYkK33NYXL +hzHaxvE+HpfDmIt6GWdXeout/IVWlAKEMqVXZTZlKC+OmRyVIg1s0rPryHiCVPNL +6WzFtIEp39rVkZLosPPcIg0T859gZqcU3osBQKKhqg1gnZRK0OvYIRTwfDf0FGAN +tGikY7XpOlEAavA9c/9eXZBV0RZdIDk2+4jZHUO+AZLUw5cR+Jp9f2YQG31FFjPb +iZY0EMx19Usle/4Mm67/kaHPK4I+cJ9VAmZXMCnRKkYHTVszb6DZWYz85oNjh1o= +=FYia +-----END PGP SIGNATURE----- diff --git a/crates/radicle-surf/src/test/platinum/signatures/initial.sig b/crates/radicle-surf/src/test/platinum/signatures/initial.sig new file mode 100644 index 000000000..0ee1f74ae --- /dev/null +++ b/crates/radicle-surf/src/test/platinum/signatures/initial.sig @@ -0,0 +1,16 @@ +-----BEGIN PGP SIGNATURE----- + +iQIzBAABCAAdFiEEime/6MCYr8AgSm0yaDIsu74NAroFAl3k5mIACgkQaDIsu74N +ArrxuA//e9riSTSzZaYcayEykaGgYxm4FAiEcs/LONQp2wJg1srs6xCEjcYHdWg0 +0eP4qE7KdUtMiXyCv4ma4+BKsM+OpH0KP58ju/c6a7AD8AMQbYoT6c9Gp7Wwkly/ +Xn2lXzM19SDBZUTfEEc6ejZiWd3DGJJs88tTstgoIdFjzHe/BEarVWDT2PBducIm +FDz/dvzoi9I97lPyCiLRP2LzCDG8vyN0T0xFJpF3aPSebVSW6CZuZdkkwDWqf22D +bFuEXtotnl+cUnYJXxTFEj0vdOLfBbeiVdtDeGRxKWNTyRmGrQrZPzRP1/WG2kPP +RMVRgonUEJMt/JzFILH14tYv1bc9ji+7xLNPRn3Z+A7KQfdphfw6/VZS5vY0wH6V +XkJEqJd6i4k/PeRwcFX3X1i7npla/pY79KtjGXDcLoa5O42JlezEzJFMN0mNxLR9 +BXenBACsP40ifsaPHl4maXCt/JqbvtLdGtths6LK/U3nIIXxRz+i/rW2ZzFc+zEF +msYzWWSj/MNSuMyfRwGmtk8F+dyTr11w+X7VrKTi5OHLkqwArdnMnLsywEsLa/lB +9QZAM+8mN3zIdr3QpBWGP/kzUC+3XaxCs4ZR5H6ILItnWHNTRY3j11cruzIFH7WV +HQAMBl95HdJebDzvS0CY7P/fntzrdnNH+/gvF1ZA3DBLuKZFA5I= +=WzFk +-----END PGP SIGNATURE----- \ No newline at end of file diff --git a/crates/radicle-surf/src/test/platinum/signatures/long-message.sig b/crates/radicle-surf/src/test/platinum/signatures/long-message.sig new file mode 100644 index 000000000..08f8b1e98 --- /dev/null +++ b/crates/radicle-surf/src/test/platinum/signatures/long-message.sig @@ -0,0 +1,10 @@ +-----BEGIN PGP SIGNATURE----- + +wsBcBAABCAAQBQJd8nTZCRBK7hj4Ov3rIwAAdHIIAFbhHXu4yTmibrAKiRLo52/4 +3jxGoVoWvJuZIrHq1KINdwifV8FcRgFvGMwHtd/ACo7QemaDiFHF4cd3/jB3FVv1 +o+ugassmwtETkl5soI7KvM9fmw3DsMBu/Kx1XPGZvSMs8VuU+bRH/5PVnrF9ck/m +P6aX2rRmf/HngxqnTPt9pHvi9/u3BEhyaQgrdVxBclzW3e1pjYUi4mPgwipNoHme +OqwhRdW0o/e2I/J50elluWULKJD+I9XfbBugNw47wzywf23OX4ex4ViO+tRua1mB +W1NWw6sFjTbra1gGgUaWMtTzxWOezbjazp/uPsNx9KscoNsnqaapkZHqZYLh8Po= +=Atpd +-----END PGP SIGNATURE----- diff --git a/crates/radicle-surf/src/test/platinum/signatures/master.sig b/crates/radicle-surf/src/test/platinum/signatures/master.sig new file mode 100644 index 000000000..81f5bfa11 --- /dev/null +++ b/crates/radicle-surf/src/test/platinum/signatures/master.sig @@ -0,0 +1,10 @@ +-----BEGIN PGP SIGNATURE----- + +wsBcBAABCAAQBQJfiHWICRBK7hj4Ov3rIwAAdHIIAEvxxPkgNdFOC3uF3w59CpkG +6Z/DGOpDrP6P8qQQ4nJ6TZZHFvIs6+4i9XyvzPflrnNPgbWJhxnLA2ylPuu5+Cft +CxwlmRuxFBKeAfFrVPBK/XtoWCnnTUCQMMcKEgO7xoBaFiRjiu3LaMI/X3u6HPEo +hTBDx4A/MBTJhphHTnJ8w9COpRoejNJLTuja7+6Q6Mz/ckwK6tzttyE9vnfHRbjL +YbhGLJL6uYnbK3yp8WbwVMKYMnfPdW5Hw5trwqVuXljMzci9ik1LWgmpnVxIkf/x +jIXElzrjbUrh9qiWpevVd5p5RwnI7bdJG4rQVvz2HPcz1tDgiV6ZNQ1G/OcwneA= +=YLNW +-----END PGP SIGNATURE----- diff --git a/crates/radicle-surf/src/test/platinum/signatures/merged.sig b/crates/radicle-surf/src/test/platinum/signatures/merged.sig new file mode 100644 index 000000000..8bf75427e --- /dev/null +++ b/crates/radicle-surf/src/test/platinum/signatures/merged.sig @@ -0,0 +1,10 @@ +-----BEGIN PGP SIGNATURE----- + +wsBcBAABCAAQBQJeb4kbCRBK7hj4Ov3rIwAAdHIIAJWI1IccDC4VfHYs8MeeGXgn +9CSM5dh6QAzILYCFPX82alftJ+wxxCccWmIJ1YltFEgy1nCvRwYp4fbeIpqxjZCc +IZwwerPIHckGPEpcDkTdQ/ER8z84HWNIqXb8GikzRZCDyRBqHNdufZ3YsjLxVfbQ +hstD4Y1t9ocn43QDc7N7pZmxqMPfFFnHwZmX5aSrkzXJ7W3sQ8pCTsGr/odKP79L +hRB9dmmmGIiB9TvnFD+2Slx1Z8frelOm9RClZ6NjPERl5ZKyHj5VqxfMi6Mo0KC4 +Qky9AZ2j9872yUEqUXD6xmBuxyYWVwnPzVe8oxk4paOLpd3x1jbS6sbtPrimaRY= +=vclq +-----END PGP SIGNATURE----- diff --git a/crates/radicle-surf/src/test/platinum/signatures/moved.sig b/crates/radicle-surf/src/test/platinum/signatures/moved.sig new file mode 100644 index 000000000..a098125be --- /dev/null +++ b/crates/radicle-surf/src/test/platinum/signatures/moved.sig @@ -0,0 +1,16 @@ +-----BEGIN PGP SIGNATURE----- + +iQIzBAABCAAdFiEEime/6MCYr8AgSm0yaDIsu74NAroFAl3k6lMACgkQaDIsu74N +Arrl/A/7BH95H9m44+86RTsm0rZZvQ40KV6vADEVEXlzqsN/Nqmkij46prjPni+k +BWypnfSZO3pmCXTzLmJ5nUEVOL+aHhIwanVeFS15OqpTKNLVzMMTXsRcsHzyXmkS +fp0AUOzurgMoeDJ11u16/Q0CiKWr0PPjwO0DxrHxkwvWXQ2NupuPdb07c+e1c+Oz +2sn+7V7HyZ9cvZSfoxJJDUiLRezQ2xx5EIygTdKlY/1wrQQ/MMYy+VSeZv60+oYf +ACrVN3X2dQMEgWEW6CTOKqeQVeGsJtgwkJqtRi/7Z3pi3hLymuIxVL1CCODq0b6Q +tw/KyYF6RXO2a9rgaY4ghEd5rTj2tpz/FvQ/3kIjOtNMDW6vaCJNNsZeJneb+5xq +yfNQ7Z7iGk+SGreLG23XhuP36LWxqQq6zFyAiRzuqKf96a3ZI0pw7gXR0AAqHzFI +eUa6B5LrmE4RNM3zKjttuvZysE8Qh18sgNrCnjxdZZyfmXIr1E38Y/drvePuLBux +ioWDTgXc1lK1MLy46p/1ub3/UxoTps4fX+iOpKWd2fRn/nE16is3y5Q5u6+dF+YW +djCe30AsDoufRsp52UrWXLFrqzqZRILKUkvk0obZwLaP+gZascv7ME7ysdMyYPzg +WVmqIk3ew/0bacqPDJZfoGTI1yYl2rTAiKxwzKOZA7oAVD51HJE= +=WX/k +-----END PGP SIGNATURE----- \ No newline at end of file diff --git a/crates/radicle-surf/src/test/platinum/signatures/nested.sig b/crates/radicle-surf/src/test/platinum/signatures/nested.sig new file mode 100644 index 000000000..a629c64c9 --- /dev/null +++ b/crates/radicle-surf/src/test/platinum/signatures/nested.sig @@ -0,0 +1,16 @@ +-----BEGIN PGP SIGNATURE----- + +iQIzBAABCAAdFiEEime/6MCYr8AgSm0yaDIsu74NAroFAl3k5s8ACgkQaDIsu74N +ArqknQ//XWUKF6n5Dl9tv8lLIGTTGzyeF0ZcI5dSE9WF6x3YHH3wSawE84KenRwE +L1PrpnQUrFw9JOeT+0aoNIvqGGj/6G82evz0bcqkyOanJiHr1SlRaZFuNwvFkbMS +4aM+pqDdzPRUynRCQmswMOPhybucvmv2NTRU4Vufh7YvaCVOXyFTR1gIprw+CtfV +Q5IWXfPeI5oQ6LLLKBnhStNK3NukyaJAkmzDkr63Z9pnFAZ48A/QqBCjDXVMkAvU +eS6WkaFSVXmtEIcLYFbB8L5a62DYjMdzfhX+LzDvUE0DADUqM5NnJW9OjIBJdrYq +Xn6pA4qLPZk0aE9lD7vJ13/nZTgouVGQNFPNhyJpasfES2SPEGWtx2TTpHxWVBC/ +BVxfIvmVZz4oPsRS1jCmbL8wB33bxAq/MqV4Qs23vTlkwInmBvuZfzLP339u+wNT +XKkCCgGkrl8UDiWNR6USPhlylJyKYhbCrZnTUPVMe/pMhp089DZyiiHPpgeT623S +U4XwYneoZmQEht5SIygiph/HqKA1RiP9Wmq2jnvLBidZ+ag3yqY10Nn1VxVvFAGb +EAbSQr2FJpaeyro87/dWJnWbAY1uBS84jFoS/3RWpV+/bqPkP7SPA/M8sCIM479z +zF9ovzyXczB4H2RlA6/vIW31Jq8jHSw4HwtCn5JKArB9eL0kVMM= +=3aUn +-----END PGP SIGNATURE----- \ No newline at end of file diff --git a/crates/radicle-surf/src/test/platinum/signatures/sources.sig b/crates/radicle-surf/src/test/platinum/signatures/sources.sig new file mode 100644 index 000000000..74531e1c9 --- /dev/null +++ b/crates/radicle-surf/src/test/platinum/signatures/sources.sig @@ -0,0 +1,16 @@ +-----BEGIN PGP SIGNATURE----- + +iQIzBAABCAAdFiEEime/6MCYr8AgSm0yaDIsu74NAroFAl3k6MQACgkQaDIsu74N +ArqgZBAAkjJdTCQzLZX/sthB3lqVatFLU+RzcEeF5Np+yMxwzMunA/VheZZffHsT +j/tEjQw/hehPb3YS2TxA8JREWqccbBgeCF9b4ZPvmEW1Hdp6S6Hj/bek4frg9oZi +rSOzjEg1wZDmGp3uIYiOD0e8p1kkMyaWZamg41HmSRBEbQTD2VANkVYCwUZ+lIHM +SZkZ4lRp5Tpg4u4r9TlS4UqWNh53S5GVdIgjAZks/THfJscPfu7AOPQF+G855DLU +6upSHni3tIBDTMkhU1PdDdsG278HglsHKWVl7Xi7XPlW+NX/bb7T8ffqUE2nKENH +MvOBMX8uEss5/c+5sq5HxgW9zGJFfVvBMvI34FlT/2HY3m+X8aEXPTssF5vvZteP +q8Mj6L6RkfpRad/9jpc1wsIN37FdudzGZ51Yqx+nuBGV7KaCVTH7YrvA0yRZ+8+P +zWfNvAFvbtdsYEVPo2J7smC9DJndA3wKgoF05BkwlYm7JHzD1yCXIixEq7Vu8Mq0 +h12E5jKmGFenTbqOWCd8FsAqWgVAgxcpTh2Pe2h6YYikZ4C2bImvmHNYXOTs5y/C +/5MggXvSy2qzA7B1j7Etwb1jDoVztrbSCRB0HQ35MJ7NAy7byxuE0ofsPJjZXZRf +sdwjJILgPx8URUVjgAD7Uowwye5ZdHTA26YL5vnu76BtwLZl5cU= +=gyZi +-----END PGP SIGNATURE----- \ No newline at end of file diff --git a/crates/radicle-surf/src/test/platinum/signatures/texts.sig b/crates/radicle-surf/src/test/platinum/signatures/texts.sig new file mode 100644 index 000000000..5b9bceb7b --- /dev/null +++ b/crates/radicle-surf/src/test/platinum/signatures/texts.sig @@ -0,0 +1,16 @@ +-----BEGIN PGP SIGNATURE----- + +iQIzBAABCAAdFiEEime/6MCYr8AgSm0yaDIsu74NAroFAl3k6ugACgkQaDIsu74N +AromTQ//eNQv4HPfCs4Q/zrWPnBgvk5JgwEaCJNBWHvKsHIWMeMeS4KQ3rTD9d1z +xicWcV5JHORe4+OdJHCcFbPFfKhUR99JxXY+OoQK8qYpT/nQsTgURciw3Ef+bbcn +WGAdlvFDpsSjfipxp2xSFwU5FGwZ9FjGG9gKhDKbEzmqiU5tp3TpnVdJej55FAtM +TdD3I00JNKmmOGPZw7DKi3Re7FqajG1FsqXsqwsq0S25TLcrPdO+hbaHHxZvCidG +1oH1p4TC/a5XWB+uIcO5Pyrk7z+HNfDtCCebKG+JCJJYH4PtdxdWI2ZKaROJshMU +JnKMBaVacGVnBjl/G9SzmYTQs3lsbT+quMgXk1lQ1R8eGJo/nuc4LOevyEAlcnxU +WOfJMHFXqCwgfJz42JezJXFTCVDoBZ7OPGUHpee5UoIpBAEDANeDAopAZhOPp1RJ +wY0YaWmn3HTZe9LXg0M1n/BUfDZgY5ZUOtXuT1Lla3ReZPGYxK4bSr6YRLhcz2Vp +20OJBDzDsZihcU2PBp7R1XwhhQGUf9mliuBBEXLD3jek3BTl9fwA+tfb0CJ7mfR4 +9i5i5PGrY32FLiBwdpAmfRhTLYh3y49EuQl14tMiRPB+5YFi1plhYzghpsgUDkpJ +NdddcQW+S4EyjxTUURPhQovlkFGW8OSJCf5CxPfMizOtaJlcFUU= +=GUKI +-----END PGP SIGNATURE----- \ No newline at end of file diff --git a/crates/radicle-surf/src/test/platinum/test.gz b/crates/radicle-surf/src/test/platinum/test.gz new file mode 100644 index 000000000..8d38a7290 Binary files /dev/null and b/crates/radicle-surf/src/test/platinum/test.gz differ diff --git a/crates/radicle-surf/src/test/reference.rs b/crates/radicle-surf/src/test/reference.rs index 6625feb97..cb3490bed 100644 --- a/crates/radicle-surf/src/test/reference.rs +++ b/crates/radicle-surf/src/test/reference.rs @@ -1,22 +1,18 @@ -use radicle_git_ext::ref_format::refspec; -use radicle_surf::{Glob, Repository}; +use crate::{Glob, Repository}; +use radicle_git_ref_format::pattern; -use super::GIT_PLATINUM; +use super::platinum; #[test] fn test_branches() { - let repo = Repository::open(GIT_PLATINUM).unwrap(); + let repo = Repository::open(platinum::get()).unwrap(); let heads = Glob::all_heads(); let branches = repo.branches(heads.clone()).unwrap(); for b in branches { println!("{}", b.unwrap().refname()); } let branches = repo - .branches( - heads - .branches() - .and(Glob::remotes(refspec::pattern!("banana/*"))), - ) + .branches(heads.branches().and(Glob::remotes(pattern!("banana/*")))) .unwrap(); for b in branches { println!("{}", b.unwrap().refname()); @@ -25,7 +21,7 @@ fn test_branches() { #[test] fn test_tag_snapshot() { - let repo = Repository::open(GIT_PLATINUM).unwrap(); + let repo = Repository::open(platinum::get()).unwrap(); let tags = repo .tags(&Glob::all_tags()) .unwrap() @@ -38,18 +34,16 @@ fn test_tag_snapshot() { #[test] fn test_namespaces() { - let repo = Repository::open(GIT_PLATINUM).unwrap(); + let repo = Repository::open(platinum::get()).unwrap(); let namespaces = repo.namespaces(&Glob::all_namespaces()).unwrap(); assert_eq!(namespaces.count(), 3); let namespaces = repo - .namespaces(&Glob::namespaces(refspec::pattern!("golden/*"))) + .namespaces(&Glob::namespaces(pattern!("golden/*"))) .unwrap(); assert_eq!(namespaces.count(), 2); let namespaces = repo - .namespaces( - &Glob::namespaces(refspec::pattern!("golden/*")).insert(refspec::pattern!("me/*")), - ) + .namespaces(&Glob::namespaces(pattern!("golden/*")).insert(pattern!("me/*"))) .unwrap(); assert_eq!(namespaces.count(), 3); } diff --git a/crates/radicle-surf/src/test/repository.rs b/crates/radicle-surf/src/test/repository.rs new file mode 100644 index 000000000..5cd55d356 --- /dev/null +++ b/crates/radicle-surf/src/test/repository.rs @@ -0,0 +1,103 @@ +use std::{convert::Infallible, path::Path}; + +use git2::{Oid, RepositoryInitOptions}; +use radicle_git_metadata::commit::CommitData; +use radicle_git_ref_format::RefString; + +use crate::test::r#gen::commit::{self, TreeData}; +pub struct Fixture { + #[allow(unused)] // Prevent early removal of the temporary directory. + dir: tempfile::TempDir, + + pub inner: git2::Repository, + pub head: Option, +} + +/// Initialise a [`git2::Repository`] in a temporary directory. +/// +/// The provided `commits` will be added to the repository, and the +/// head commit will be returned. +pub fn fixture(refname: &RefString, commits: Vec>) -> Fixture { + let dir = tempfile::tempdir().unwrap(); + let repo = git2::Repository::init_opts( + dir.path(), + RepositoryInitOptions::new().initial_head(refname), + ) + .unwrap(); + let commits = commit::write_commits(&repo, commits).unwrap(); + let head = commits.last().copied(); + + if let Some(head) = head { + repo.reference(refname.as_str(), head, false, "Initialise repository") + .unwrap(); + } + + Fixture { + dir, + inner: repo, + head, + } +} + +pub fn bare_fixture( + refname: &RefString, + commits: Vec>, +) -> Fixture { + let dir = tempfile::tempdir().unwrap(); + let repo = git2::Repository::init_opts( + dir.path(), + RepositoryInitOptions::new() + .initial_head(refname) + .bare(true), + ) + .unwrap(); + let commits = commit::write_commits(&repo, commits).unwrap(); + let head = commits.last().copied(); + + if let Some(head) = head { + repo.reference(refname.as_str(), head, false, "Initialise repository") + .unwrap(); + } + + Fixture { + dir, + inner: repo, + head, + } +} + +pub fn submodule<'a>( + parent: &'a git2::Repository, + child: &'a git2::Repository, + refname: &RefString, + head: Oid, + author: &git2::Signature, +) -> git2::Submodule<'a> { + let url = format!("file://{}", child.path().canonicalize().unwrap().display()); + let mut sub = parent + .submodule(url.as_str(), Path::new("submodule"), true) + .unwrap(); + let _ = sub.open().unwrap(); + let _ = sub + .clone(Some(&mut git2::SubmoduleUpdateOptions::default())) + .unwrap(); + sub.add_to_index(true).unwrap(); + sub.add_finalize().unwrap(); + { + let mut ix = parent.index().unwrap(); + let tree = ix.write_tree_to(parent).unwrap(); + let tree = parent.find_tree(tree).unwrap(); + let head = parent.find_commit(head).unwrap(); + parent + .commit( + Some(refname.as_str()), + author, + author, + "Commit submodule", + &tree, + &[&head], + ) + .unwrap(); + } + sub +} diff --git a/crates/radicle-surf/src/test/rev.rs b/crates/radicle-surf/src/test/rev.rs index 60294a0f0..81d7a23ee 100644 --- a/crates/radicle-surf/src/test/rev.rs +++ b/crates/radicle-surf/src/test/rev.rs @@ -1,9 +1,10 @@ use std::str::FromStr; -use radicle_git_ext::ref_format::{name::component, refname}; -use radicle_surf::{Branch, Error, Oid, Repository}; +use radicle_git_ref_format::{component, refname}; -use super::GIT_PLATINUM; +use crate::{Branch, Error, Oid, Repository}; + +use super::platinum; // **FIXME**: This seems to break occasionally on // buildkite. For some reason the commit @@ -18,7 +19,7 @@ use super::GIT_PLATINUM; // * Expand "Options" and select "clean checkout". #[test] fn _master() -> Result<(), Error> { - let repo = Repository::open(GIT_PLATINUM)?; + let repo = Repository::open(platinum::get())?; let mut history = repo.history(Branch::remote(component!("origin"), refname!("master")))?; let commit1 = Oid::from_str("3873745c8f6ffb45c990eb23b491d4b4b6182f95")?; @@ -26,7 +27,7 @@ fn _master() -> Result<(), Error> { history.any(|commit| commit.unwrap().id == commit1), "commit_id={}, history =\n{:#?}", commit1, - &history + history ); let commit2 = Oid::from_str("d6880352fc7fda8f521ae9b7357668b17bb5bad5")?; @@ -34,7 +35,7 @@ fn _master() -> Result<(), Error> { history.any(|commit| commit.unwrap().id == commit2), "commit_id={}, history =\n{:#?}", commit2, - &history + history ); Ok(()) @@ -42,7 +43,7 @@ fn _master() -> Result<(), Error> { #[test] fn commit() -> Result<(), Error> { - let repo = Repository::open(GIT_PLATINUM)?; + let repo = Repository::open(platinum::get())?; let rev = Oid::from_str("3873745c8f6ffb45c990eb23b491d4b4b6182f95")?; let mut history = repo.history(rev)?; @@ -54,7 +55,7 @@ fn commit() -> Result<(), Error> { #[test] fn commit_parents() -> Result<(), Error> { - let repo = Repository::open(GIT_PLATINUM)?; + let repo = Repository::open(platinum::get())?; let rev = Oid::from_str("3873745c8f6ffb45c990eb23b491d4b4b6182f95")?; let history = repo.history(rev)?; let commit = history.head(); @@ -69,7 +70,7 @@ fn commit_parents() -> Result<(), Error> { #[test] fn commit_short() -> Result<(), Error> { - let repo = Repository::open(GIT_PLATINUM)?; + let repo = Repository::open(platinum::get())?; let rev = repo.oid("3873745c8")?; let mut history = repo.history(rev)?; @@ -81,7 +82,7 @@ fn commit_short() -> Result<(), Error> { #[test] fn tag() -> Result<(), Error> { - let repo = Repository::open(GIT_PLATINUM)?; + let repo = Repository::open(platinum::get())?; let rev = refname!("refs/tags/v0.2.0"); let history = repo.history(&rev)?; diff --git a/crates/radicle-surf/src/test/roundtrip.rs b/crates/radicle-surf/src/test/roundtrip.rs new file mode 100644 index 000000000..3a054d6e8 --- /dev/null +++ b/crates/radicle-surf/src/test/roundtrip.rs @@ -0,0 +1,12 @@ +use std::fmt::Debug; + +#[cfg(feature = "serde")] +pub fn json(a: A) +where + for<'de> A: Debug + PartialEq + serde::Serialize + serde::Deserialize<'de>, +{ + assert_eq!( + a, + serde_json::from_str(&serde_json::to_string(&a).unwrap()).unwrap() + ) +} diff --git a/crates/radicle-surf/src/test/source.rs b/crates/radicle-surf/src/test/source.rs index 4b97714ab..6b8918016 100644 --- a/crates/radicle-surf/src/test/source.rs +++ b/crates/radicle-surf/src/test/source.rs @@ -1,14 +1,12 @@ use std::path::PathBuf; -use radicle_git_ext::ref_format::refname; -use radicle_surf::{Branch, Glob, Repository}; +use crate::{Branch, Glob, Repository, test::platinum}; +use radicle_git_ref_format::refname; use serde_json::json; -const GIT_PLATINUM: &str = "../data/git-platinum"; - #[test] fn tree_serialization() { - let repo = Repository::open(GIT_PLATINUM).unwrap(); + let repo = Repository::open(platinum::get()).unwrap(); let tree = repo.tree(refname!("refs/heads/master"), &"src").unwrap(); let expected = json!({ @@ -59,7 +57,7 @@ fn tree_serialization() { #[test] fn test_tree_last_commit() { - let repo = Repository::open(GIT_PLATINUM).unwrap(); + let repo = Repository::open(platinum::get()).unwrap(); let tree = repo.tree(refname!("refs/heads/master"), &"src").unwrap(); let last_commit = tree.last_commit(&repo).unwrap(); assert_ne!(*tree.commit(), last_commit); @@ -71,7 +69,7 @@ fn test_tree_last_commit() { #[test] fn repo_tree_empty_branch() { - let repo = Repository::open(GIT_PLATINUM).unwrap(); + let repo = Repository::open(platinum::get()).unwrap(); let rev = Branch::local(refname!("empty-branch")); let tree = repo.tree(rev, &"").unwrap(); assert_eq!(tree.entries().len(), 0); @@ -85,7 +83,7 @@ fn repo_tree_empty_branch() { #[test] fn repo_tree() { - let repo = Repository::open(GIT_PLATINUM).unwrap(); + let repo = Repository::open(platinum::get()).unwrap(); let tree = repo .tree("27acd68c7504755aa11023300890bb85bbd69d45", &"src") .unwrap(); @@ -132,7 +130,7 @@ fn repo_tree() { #[test] fn repo_blob() { - let repo = Repository::open(GIT_PLATINUM).unwrap(); + let repo = Repository::open(platinum::get()).unwrap(); let blob = repo .blob("27acd68c7504755aa11023300890bb85bbd69d45", &"src/memory.rs") .unwrap(); @@ -171,7 +169,7 @@ fn repo_blob() { #[test] fn tree_ordering() { - let repo = Repository::open(GIT_PLATINUM).unwrap(); + let repo = Repository::open(platinum::get()).unwrap(); let tree = repo .tree(refname!("refs/heads/master"), &PathBuf::new()) .unwrap(); @@ -195,7 +193,7 @@ fn tree_ordering() { #[test] fn commit_branches() { - let repo = Repository::open(GIT_PLATINUM).unwrap(); + let repo = Repository::open(platinum::get()).unwrap(); let init_commit = "d3464e33d75c75c99bfb90fa2e9d16efc0b7d0e3"; let glob = Glob::all_heads().branches().and(Glob::all_remotes()); let branches = repo.revision_branches(init_commit, glob).unwrap(); diff --git a/crates/radicle-surf/src/test/submodule.rs b/crates/radicle-surf/src/test/submodule.rs index 62129b8f6..a2dd637a7 100644 --- a/crates/radicle-surf/src/test/submodule.rs +++ b/crates/radicle-surf/src/test/submodule.rs @@ -1,17 +1,19 @@ use std::{convert::Infallible, path::Path}; use proptest::{collection, proptest}; -use radicle_git_ext::commit::CommitData; -use radicle_git_ext::ref_format::refname; -use radicle_git_ext_test::gen; -use radicle_surf::tree::EntryKind; -use radicle_surf::{fs, Branch, Repository}; +use radicle_git_metadata::commit::CommitData; +use radicle_git_ref_format::refname; + +use crate::tree::EntryKind; +use crate::{Branch, Repository, fs}; + +use super::r#gen; proptest! { #[test] fn test_submodule( - initial in gen::commit::commit(), - commits in collection::vec(gen::commit::commit(), 1..5) + initial in r#gen::commit::commit(), + commits in collection::vec(r#gen::commit::commit(), 1..5) ) { prop::test_submodule(initial, commits) } @@ -19,8 +21,8 @@ proptest! { #[ignore = "segfault"] #[test] fn test_submodule_bare( - initial in gen::commit::commit(), - commits in collection::vec(gen::commit::commit(), 1..5) + initial in r#gen::commit::commit(), + commits in collection::vec(r#gen::commit::commit(), 1..5) ) { prop::test_submodule_bare(initial, commits) } @@ -28,7 +30,8 @@ proptest! { } mod prop { - use radicle_git_ext_test::{gen::commit, repository}; + use crate::test::r#gen::commit; + use crate::test::repository; use super::*; @@ -39,12 +42,11 @@ mod prop { let refname = refname!("refs/heads/master"); let author = git2::Signature::try_from(initial.author()).unwrap(); - let submodule = repository::fixture(&refname, commits).unwrap(); - let repo = repository::fixture(&refname, vec![initial]).unwrap(); + let submodule = repository::fixture(&refname, commits); + let repo = repository::fixture(&refname, vec![initial]); let head = repo.head.expect("missing initial commit"); - let sub = - repository::submodule(&repo.inner, &submodule.inner, &refname, head, &author).unwrap(); + let sub = repository::submodule(&repo.inner, &submodule.inner, &refname, head, &author); let repo = Repository::open(repo.inner.path()).unwrap(); let branch = Branch::local(refname); @@ -65,12 +67,11 @@ mod prop { let refname = refname!("refs/heads/master"); let author = git2::Signature::try_from(initial.author()).unwrap(); - let submodule = repository::fixture(&refname, commits).unwrap(); - let repo = repository::bare_fixture(&refname, vec![initial]).unwrap(); + let submodule = repository::fixture(&refname, commits); + let repo = repository::bare_fixture(&refname, vec![initial]); let head = repo.head.expect("missing initial commit"); - let sub = - repository::submodule(&repo.inner, &submodule.inner, &refname, head, &author).unwrap(); + let sub = repository::submodule(&repo.inner, &submodule.inner, &refname, head, &author); let repo = Repository::open(repo.inner.path()).unwrap(); let branch = Branch::local(refname); diff --git a/crates/radicle-surf/src/test/threading.rs b/crates/radicle-surf/src/test/threading.rs index 47cca4859..d3c798c1d 100644 --- a/crates/radicle-surf/src/test/threading.rs +++ b/crates/radicle-surf/src/test/threading.rs @@ -1,13 +1,14 @@ use std::sync::{Mutex, MutexGuard}; -use radicle_git_ext::ref_format::{name::component, refname}; -use radicle_surf::{Branch, Error, Glob, Repository}; +use radicle_git_ref_format::{component, refname}; -use super::GIT_PLATINUM; +use crate::{Branch, Error, Glob, Repository}; + +use super::platinum; #[test] fn basic_test() -> Result<(), Error> { - let shared_repo = Mutex::new(Repository::open(GIT_PLATINUM)?); + let shared_repo = Mutex::new(Repository::open(platinum::get())?); let locked_repo: MutexGuard = shared_repo.lock().unwrap(); let mut branches = locked_repo .branches(Glob::all_heads().branches().and(Glob::all_remotes()))? diff --git a/crates/radicle-surf/src/tree.rs b/crates/radicle-surf/src/tree.rs index 2f691d71c..8e65ad349 100644 --- a/crates/radicle-surf/src/tree.rs +++ b/crates/radicle-surf/src/tree.rs @@ -4,15 +4,15 @@ use std::cmp::Ordering; use std::path::PathBuf; -use radicle_git_ext::Oid; +use radicle_oid::Oid; #[cfg(feature = "serde")] use serde::{ - ser::{SerializeStruct as _, Serializer}, Serialize, + ser::{SerializeStruct as _, Serializer}, }; use url::Url; -use crate::{fs, Commit, Error, Repository}; +use crate::{Commit, Error, Repository, fs}; /// Represents a tree object as in git. It is essentially the content of /// one directory. Note that multiple directories can have the same content,