merge radicle-source into radicle-surf

Initially, radicle-source was envisioned to be another layer on top
of radicle-surf, however, it ended up duplicating a lot of concepts.

We consolidate them by merging radicle-source into radicle-surf.
This meant removing modules branch.rs, tag.rs, oid.rs and error.rs.
This commit is contained in:
Han Xu
2022-09-21 17:07:06 -07:00
parent ff97333d0a
commit eb1653cdb7
19 changed files with 184 additions and 395 deletions
+220
View File
@@ -0,0 +1,220 @@
// This file is part of radicle-surf
// <https://github.com/radicle-dev/radicle-surf>
//
// Copyright (C) 2019-2020 The Radicle Team <dev@radicle.xyz>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 or
// later as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//! Represents git object type 'blob', i.e. actual file contents.
//! See git [doc](https://git-scm.com/book/en/v2/Git-Internals-Git-Objects) for more details.
use std::{
convert::TryFrom as _,
str::{self, FromStr as _},
};
#[cfg(feature = "serialize")]
use serde::{
ser::{SerializeStruct as _, Serializer},
Serialize,
};
use crate::{
commit,
file_system,
object::{Error, Info, ObjectType},
revision::Revision,
vcs::git::{Browser, Rev},
};
#[cfg(feature = "syntax")]
use crate::syntax;
/// File data abstraction.
pub struct Blob {
/// Actual content of the file, if the content is ASCII.
pub content: BlobContent,
/// Extra info for the file.
pub info: Info,
/// Absolute path to the object from the root of the repo.
pub path: String,
}
impl Blob {
/// Indicates if the content of the [`Blob`] is binary.
#[must_use]
pub fn is_binary(&self) -> bool {
matches!(self.content, BlobContent::Binary(_))
}
/// Indicates if the content of the [`Blob`] is HTML.
#[must_use]
pub const fn is_html(&self) -> bool {
matches!(self.content, BlobContent::Html(_))
}
}
#[cfg(feature = "serialize")]
impl Serialize for Blob {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_struct("Blob", 5)?;
state.serialize_field("binary", &self.is_binary())?;
state.serialize_field("html", &self.is_html())?;
state.serialize_field("content", &self.content)?;
state.serialize_field("info", &self.info)?;
state.serialize_field("path", &self.path)?;
state.end()
}
}
/// Variants of blob content.
#[derive(PartialEq, Eq)]
pub enum BlobContent {
/// Content is plain text and can be passed as a string.
Plain(String),
/// Content is syntax-highlighted HTML.
///
/// Note that is necessary to enable the `syntax` feature flag for this
/// variant to be constructed. Use `highlighting::blob`, instead of
/// [`blob`] to get highlighted content.
Html(String),
/// Content is binary and needs special treatment.
Binary(Vec<u8>),
}
#[cfg(feature = "serialize")]
impl Serialize for BlobContent {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::Plain(content) | Self::Html(content) => serializer.serialize_str(content),
Self::Binary(bytes) => {
let encoded = base64::encode(bytes);
serializer.serialize_str(&encoded)
},
}
}
}
/// Returns the [`Blob`] for a file at `revision` under `path`.
///
/// # Errors
///
/// Will return [`Error`] if the project doesn't exist or a surf interaction
/// fails.
pub fn blob<P>(
browser: &mut Browser,
maybe_revision: Option<Revision<P>>,
path: &str,
) -> Result<Blob, Error>
where
P: ToString,
{
make_blob(browser, maybe_revision, path, content)
}
fn make_blob<P, C>(
browser: &mut Browser,
maybe_revision: Option<Revision<P>>,
path: &str,
content: C,
) -> Result<Blob, Error>
where
P: ToString,
C: FnOnce(&[u8]) -> BlobContent,
{
let maybe_revision = maybe_revision.map(Rev::try_from).transpose()?;
if let Some(revision) = maybe_revision {
browser.rev(revision)?;
}
let root = browser.get_directory()?;
let p = file_system::Path::from_str(path)?;
let file = root
.find_file(p.clone())
.ok_or_else(|| Error::PathNotFound(p.clone()))?;
let mut commit_path = file_system::Path::root();
commit_path.append(p.clone());
let last_commit = browser
.last_commit(commit_path)?
.map(|c| commit::Header::from(&c));
let (_rest, last) = p.split_last();
let content = content(&file.contents);
Ok(Blob {
content,
info: Info {
name: last.to_string(),
object_type: ObjectType::Blob,
last_commit,
},
path: path.to_string(),
})
}
/// Return a [`BlobContent`] given a byte slice.
fn content(content: &[u8]) -> BlobContent {
match str::from_utf8(content) {
Ok(utf8) => BlobContent::Plain(utf8.to_owned()),
Err(_) => BlobContent::Binary(content.to_owned()),
}
}
#[cfg(feature = "syntax")]
pub mod highlighting {
use super::*;
/// Returns the [`Blob`] for a file at `revision` under `path`.
///
/// # Errors
///
/// Will return [`Error`] if the project doesn't exist or a surf interaction
/// fails.
pub fn blob<P>(
browser: &mut Browser,
maybe_revision: Option<Revision<P>>,
path: &str,
theme: Option<&str>,
) -> Result<Blob, Error>
where
P: ToString,
{
make_blob(browser, maybe_revision, path, |contents| {
content(path, contents, theme)
})
}
/// Return a [`BlobContent`] given a file path, content and theme. Attempts
/// to perform syntax highlighting when the theme is `Some`.
fn content(path: &str, content: &[u8], theme_name: Option<&str>) -> BlobContent {
let content = match str::from_utf8(content) {
Ok(content) => content,
Err(_) => return BlobContent::Binary(content.to_owned()),
};
match theme_name {
None => BlobContent::Plain(content.to_owned()),
Some(theme) => syntax::highlight(path, content, theme)
.map_or_else(|| BlobContent::Plain(content.to_owned()), BlobContent::Html),
}
}
}
+179
View File
@@ -0,0 +1,179 @@
// This file is part of radicle-surf
// <https://github.com/radicle-dev/radicle-surf>
//
// Copyright (C) 2019-2020 The Radicle Team <dev@radicle.xyz>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 or
// later as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//! Represents git object type 'tree', i.e. like directory entries in Unix.
//! See git [doc](https://git-scm.com/book/en/v2/Git-Internals-Git-Objects) for more details.
use std::{convert::TryFrom as _, str::FromStr as _};
#[cfg(feature = "serialize")]
use serde::{
ser::{SerializeStruct as _, Serializer},
Serialize,
};
use crate::{
commit,
file_system,
object::{Error, Info, ObjectType},
revision::Revision,
vcs::git::{Browser, Rev},
};
/// Result of a directory listing, carries other trees and blobs.
pub struct Tree {
/// Absolute path to the tree object from the repo root.
pub path: String,
/// Entries listed in that tree result.
pub entries: Vec<TreeEntry>,
/// Extra info for the tree object.
pub info: Info,
}
#[cfg(feature = "serialize")]
impl Serialize for Tree {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_struct("Tree", 3)?;
state.serialize_field("path", &self.path)?;
state.serialize_field("entries", &self.entries)?;
state.serialize_field("info", &self.info)?;
state.end()
}
}
// TODO(xla): Ensure correct by construction.
/// Entry in a Tree result.
pub struct TreeEntry {
/// Extra info for the entry.
pub info: Info,
/// Absolute path to the object from the root of the repo.
pub path: String,
}
#[cfg(feature = "serialize")]
impl Serialize for TreeEntry {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_struct("Tree", 2)?;
state.serialize_field("path", &self.path)?;
state.serialize_field("info", &self.info)?;
state.end()
}
}
/// Retrieve the [`Tree`] for the given `revision` and directory `prefix`.
///
/// # Errors
///
/// Will return [`Error`] if any of the surf interactions fail.
pub fn tree<P>(
browser: &mut Browser<'_>,
maybe_revision: Option<Revision<P>>,
maybe_prefix: Option<String>,
) -> Result<Tree, Error>
where
P: ToString,
{
let maybe_revision = maybe_revision.map(Rev::try_from).transpose()?;
let prefix = maybe_prefix.unwrap_or_default();
if let Some(revision) = maybe_revision {
browser.rev(revision)?;
}
let path = if prefix == "/" || prefix.is_empty() {
file_system::Path::root()
} else {
file_system::Path::from_str(&prefix)?
};
let root_dir = browser.get_directory()?;
let prefix_dir = if path.is_root() {
root_dir
} else {
root_dir
.find_directory(path.clone())
.ok_or_else(|| Error::PathNotFound(path.clone()))?
};
let mut prefix_contents = prefix_dir.list_directory();
prefix_contents.sort();
let entries_results: Result<Vec<TreeEntry>, Error> = prefix_contents
.iter()
.map(|(label, system_type)| {
let entry_path = if path.is_root() {
file_system::Path::new(label.clone())
} else {
let mut p = path.clone();
p.push(label.clone());
p
};
let mut commit_path = file_system::Path::root();
commit_path.append(entry_path.clone());
let info = Info {
name: label.to_string(),
object_type: match system_type {
file_system::SystemType::Directory => ObjectType::Tree,
file_system::SystemType::File => ObjectType::Blob,
},
last_commit: None,
};
Ok(TreeEntry {
info,
path: entry_path.to_string(),
})
})
.collect();
let mut entries = entries_results?;
// We want to ensure that in the response Tree entries come first. `Ord` being
// derived on the enum ensures Variant declaration order.
//
// https://doc.rust-lang.org/std/cmp/trait.Ord.html#derivable
entries.sort_by(|a, b| a.info.object_type.cmp(&b.info.object_type));
let last_commit = if path.is_root() {
Some(commit::Header::from(browser.get().first()))
} else {
None
};
let name = if path.is_root() {
"".into()
} else {
let (_first, last) = path.split_last();
last.to_string()
};
let info = Info {
name,
object_type: ObjectType::Tree,
last_commit,
};
Ok(Tree {
path: prefix,
entries,
info,
})
}