JavaScript is disabled, refresh for a better experience. ambee/giterated

ambee/giterated

Git repository hosting, collaboration, and discovery for the Fediverse.

Remove unneeded logs

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨cfba404

⁨giterated-models/src/repository/mod.rs⁩ - ⁨8492⁩ bytes
Raw
1 use std::fmt::{Display, Formatter};
2 use std::str::FromStr;
3
4 use serde::{Deserialize, Serialize};
5
6 use crate::object::GiteratedObject;
7
8 use super::{instance::Instance, user::User};
9
10 mod operations;
11 mod settings;
12 mod values;
13
14 pub use operations::*;
15 pub use settings::*;
16 pub use values::*;
17
18 /// A repository, defined by the instance it exists on along with
19 /// its owner and name.
20 ///
21 /// # Textual Format
22 /// A repository's textual reference is defined as:
23 ///
24 /// `{owner: User}/{name: String}@{instance: Instance}`
25 ///
26 /// # Examples
27 /// For the repository named `foo` owned by `barson:giterated.dev` on the instance
28 /// `giterated.dev`, the following [`Repository`] initialization would
29 /// be valid:
30 ///
31 /// ```
32 //# use giterated_models::model::repository::Repository;
33 //# use giterated_models::model::instance::Instance;
34 //# use giterated_models::model::user::User;
35 /// let repository = Repository {
36 /// owner: User::from_str("barson:giterated.dev").unwrap(),
37 /// name: String::from("foo"),
38 /// instance: Instance::from_str("giterated.dev").unwrap()
39 /// };
40 ///
41 /// // This is correct
42 /// assert_eq!(Repository::from_str("barson:giterated.dev/[email protected]").unwrap(), repository);
43 /// ```
44 #[derive(Hash, Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
45 pub struct Repository {
46 pub owner: User,
47 pub name: String,
48 /// Instance the repository is on
49 pub instance: Instance,
50 }
51
52 impl Display for Repository {
53 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
54 f.write_str(&format!("{}/{}@{}", self.owner, self.name, self.instance))
55 }
56 }
57
58 impl GiteratedObject for Repository {
59 fn object_name() -> &'static str {
60 "repository"
61 }
62
63 fn from_object_str(object_str: &str) -> Result<Self, anyhow::Error> {
64 Ok(Repository::from_str(object_str)?)
65 }
66 }
67
68 impl TryFrom<String> for Repository {
69 type Error = RepositoryParseError;
70
71 fn try_from(value: String) -> Result<Self, Self::Error> {
72 Self::from_str(&value)
73 }
74 }
75
76 impl FromStr for Repository {
77 type Err = RepositoryParseError;
78
79 fn from_str(s: &str) -> Result<Self, Self::Err> {
80 let mut by_ampersand = s.split('@');
81 let mut path_split = by_ampersand.next().ok_or(RepositoryParseError)?.split('/');
82
83 let instance = Instance::from_str(by_ampersand.next().ok_or(RepositoryParseError)?)
84 .map_err(|_| RepositoryParseError)?;
85 let owner = User::from_str(path_split.next().ok_or(RepositoryParseError)?)
86 .map_err(|_| RepositoryParseError)?;
87 let name = path_split.next().ok_or(RepositoryParseError)?.to_string();
88
89 Ok(Self {
90 instance,
91 owner,
92 name,
93 })
94 }
95 }
96
97 #[derive(Debug, thiserror::Error)]
98 #[error("no parse!")]
99 pub struct RepositoryParseError;
100
101 /// Visibility of the repository to the general eye
102 #[derive(PartialEq, Eq, Debug, Hash, Serialize, Deserialize, Clone, sqlx::Type)]
103 #[sqlx(type_name = "visibility", rename_all = "lowercase")]
104 pub enum RepositoryVisibility {
105 Public,
106 Unlisted,
107 Private,
108 }
109
110 /// Implements [`Display`] for [`RepositoryVisiblity`] using [`Debug`]
111 impl Display for RepositoryVisibility {
112 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
113 write!(f, "{:?}", self)
114 }
115 }
116
117 #[derive(Clone, Debug, Serialize, Deserialize)]
118 pub struct RepositoryView {
119 /// Name of the repository
120 ///
121 /// This is different than the [`Repository`] name,
122 /// which may be a path.
123 pub name: String,
124 /// Owner of the Repository
125 pub owner: User,
126 /// Repository description
127 pub description: Option<Description>,
128 /// Repository visibility
129 pub visibility: Visibility,
130 /// Default branch of the repository
131 pub default_branch: DefaultBranch,
132 /// Last commit made to the repository
133 pub latest_commit: Option<LatestCommit>,
134 /// Revision of the displayed tree
135 pub tree_rev: Option<String>,
136 /// Repository tree
137 pub tree: Vec<RepositoryTreeEntry>,
138 }
139
140 #[derive(Clone, Debug, Serialize, Deserialize)]
141 pub struct RepositoryFile {
142 /// Content of the file
143 pub content: Vec<u8>,
144 /// If the file is binary or not
145 pub binary: bool,
146 /// File size in bytes
147 pub size: usize,
148 }
149
150 #[derive(Clone, Debug, Serialize, Deserialize)]
151 pub struct RepositoryDiff {
152 /// Total number of files changed
153 pub files_changed: usize,
154 /// Total number of insertions
155 pub insertions: usize,
156 /// Total number of deletions
157 pub deletions: usize,
158 /// Preferably unified patch, probably a git patch.
159 pub patch: String,
160 }
161
162 #[derive(Debug, Clone, Serialize, Deserialize)]
163 pub enum RepositoryObjectType {
164 Tree,
165 Blob,
166 }
167
168 /// Stored info for our tree entries
169 #[derive(Debug, Clone, Serialize, Deserialize)]
170 pub struct RepositoryTreeEntry {
171 /// ID of the tree/blob
172 pub id: String,
173 /// Name of the tree/blob
174 pub name: String,
175 /// Type of the tree entry
176 pub object_type: RepositoryObjectType,
177 /// Git supplies us with the mode at all times, and people like it displayed.
178 pub mode: i32,
179 /// File size
180 pub size: Option<usize>,
181 /// Last commit made to the tree/blob
182 pub last_commit: Option<Commit>,
183 }
184
185 impl RepositoryTreeEntry {
186 pub fn new(id: &str, name: &str, object_type: RepositoryObjectType, mode: i32) -> Self {
187 Self {
188 id: id.to_string(),
189 name: name.to_string(),
190 object_type,
191 mode,
192 size: None,
193 last_commit: None,
194 }
195 }
196 }
197
198 #[derive(Debug, Clone, Serialize, Deserialize)]
199 pub struct RepositoryTreeEntryWithCommit {
200 pub tree_entry: RepositoryTreeEntry,
201 pub commit: Commit,
202 }
203
204 /// Info about a git commit
205 #[derive(PartialEq, Hash, Eq, Debug, Clone, Serialize, Deserialize)]
206 pub struct Commit {
207 /// Unique commit ID
208 pub oid: String,
209 /// Shortened abbreviated OID
210 /// This starts at the git config's "core.abbrev" length (default 7 characters) and
211 /// iteratively extends to a longer string if that length is ambiguous. The
212 /// result will be unambiguous (at least until new objects are added to the repository).
213 pub short_oid: String,
214 /// Full commit message
215 pub message: Option<String>,
216 /// Who created the commit
217 pub author: CommitSignature,
218 /// Who committed the commit
219 pub committer: CommitSignature,
220 /// Time when the commit happened
221 pub time: chrono::NaiveDateTime,
222 }
223
224 /// Gets all info from [`git2::Commit`] for easy use
225 impl From<git2::Commit<'_>> for Commit {
226 fn from(commit: git2::Commit<'_>) -> Self {
227 Self {
228 oid: commit.id().to_string(),
229 // This shouldn't ever fail, as we already know the object has an oid.
230 short_oid: commit
231 .as_object()
232 .short_id()
233 .unwrap()
234 .as_str()
235 .unwrap()
236 .to_string(),
237 message: commit.message().map(|message| message.to_string()),
238 author: commit.author().into(),
239 committer: commit.committer().into(),
240 time: chrono::NaiveDateTime::from_timestamp_opt(commit.time().seconds(), 0).unwrap(),
241 }
242 }
243 }
244
245 /// Git commit signature
246 #[derive(PartialEq, Hash, Eq, Debug, Clone, Serialize, Deserialize)]
247 pub struct CommitSignature {
248 pub name: Option<String>,
249 pub email: Option<String>,
250 pub time: chrono::NaiveDateTime,
251 }
252
253 /// Converts the signature from git2 into something usable without explicit lifetimes.
254 impl From<git2::Signature<'_>> for CommitSignature {
255 fn from(signature: git2::Signature<'_>) -> Self {
256 Self {
257 name: signature.name().map(|name| name.to_string()),
258 email: signature.email().map(|email| email.to_string()),
259 time: chrono::NaiveDateTime::from_timestamp_opt(signature.when().seconds(), 0).unwrap(),
260 }
261 }
262 }
263
264 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
265 pub struct RepositorySummary {
266 pub repository: Repository,
267 pub owner: User,
268 pub visibility: RepositoryVisibility,
269 pub description: Option<String>,
270 pub last_commit: Option<Commit>,
271 }
272
273 #[derive(Clone, Debug, Serialize, Deserialize)]
274 pub struct IssueLabel {
275 pub name: String,
276 pub color: String,
277 }
278
279 #[derive(Clone, Debug, Serialize, Deserialize)]
280 pub struct RepositoryIssue {
281 pub author: User,
282 pub id: u64,
283 pub title: String,
284 pub contents: String,
285 pub labels: Vec<IssueLabel>,
286 }
287