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

ambee/giterated

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

Experimental repository diff structure

erremilia - ⁨2⁩ years ago

parent: tbd commit: ⁨0ef533d

⁨giterated-models/src/repository/mod.rs⁩ - ⁨11636⁩ 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 /// "to" side of the diff commit
153 pub new_commit: Commit,
154 /// Total number of files changed
155 pub files_changed: usize,
156 /// Total number of insertions
157 pub insertions: usize,
158 /// Total number of deletions
159 pub deletions: usize,
160 /// List of changed files
161 pub files: Vec<RepositoryDiffFile>,
162 }
163
164 /// Represents the type of change made to a [`RepositoryDiffFile`]
165 #[derive(Clone, Debug, Serialize, Deserialize)]
166 pub enum RepositoryDiffFileStatus {
167 /// No changes
168 Unmodified,
169 /// Content changed between old and new
170 Modified,
171 /// Renamed between old and new
172 Renamed,
173 /// Copied from another old entry
174 Copied,
175 /// Ignored item in workdir
176 Ignored,
177 /// Untracked item in workdir
178 Untracked,
179 /// Type of file changed between old and new
180 Typechange,
181 /// File is unreadable
182 Unreadable,
183 /// File in the index is conflicted
184 Conflicted,
185 }
186
187 impl From<git2::Delta> for RepositoryDiffFileStatus {
188 fn from(status: git2::Delta) -> Self {
189 match status {
190 git2::Delta::Unmodified => Self::Unmodified,
191 git2::Delta::Modified => Self::Modified,
192 git2::Delta::Renamed => Self::Renamed,
193 git2::Delta::Copied => Self::Copied,
194 git2::Delta::Ignored => Self::Ignored,
195 git2::Delta::Untracked => Self::Untracked,
196 git2::Delta::Typechange => Self::Typechange,
197 git2::Delta::Unreadable => Self::Unreadable,
198 git2::Delta::Conflicted => Self::Conflicted,
199 _ => unreachable!(),
200 }
201 }
202 }
203
204 /// Represents a single file of a diff
205 #[derive(Clone, Debug, Serialize, Deserialize)]
206 pub struct RepositoryDiffFile {
207 /// The type of change made to this file
208 pub status: RepositoryDiffFileStatus,
209 /// "From" side of the diff, can be nonexistent if file for example got added for the first time
210 pub old_file_info: Option<RepositoryDiffFileInfo>,
211 /// "To" side of the diff, can be nonexistent if file got removed
212 pub new_file_info: Option<RepositoryDiffFileInfo>,
213 /// Individual chunks of changes in this file
214 pub chunks: Vec<RepositoryDiffFileChunk>,
215 }
216
217 /// Represents one side of a file diff
218 #[derive(Clone, Debug, Serialize, Deserialize)]
219 pub struct RepositoryDiffFileInfo {
220 /// ID of the file
221 pub id: String,
222 /// Path of the entry relative to the working directory of the repository
223 pub path: String,
224 /// Size in bytes
225 pub size: u64,
226 /// If the file is binary or not
227 pub binary: bool,
228 }
229
230 /// Represents a single chunk of a file diff
231 #[derive(Clone, Debug, Serialize, Deserialize)]
232 pub struct RepositoryDiffFileChunk {
233 /// Starting line number of the old file
234 pub old_start: u32,
235 /// Number of lines in "from" side of this chunk
236 pub old_lines: u32,
237 /// Starting line number of the new file
238 pub new_start: u32,
239 /// Number of lines in "to" side of this chunk
240 pub new_lines: u32,
241 /// Lines of the chunk
242 pub lines: Vec<String>,
243 }
244
245 #[derive(Debug, Clone, Serialize, Deserialize)]
246 pub enum RepositoryObjectType {
247 Tree,
248 Blob,
249 }
250
251 /// Stored info for our tree entries
252 #[derive(Debug, Clone, Serialize, Deserialize)]
253 pub struct RepositoryTreeEntry {
254 /// ID of the tree/blob
255 pub id: String,
256 /// Name of the tree/blob
257 pub name: String,
258 /// Type of the tree entry
259 pub object_type: RepositoryObjectType,
260 /// Git supplies us with the mode at all times, and people like it displayed.
261 pub mode: i32,
262 /// File size
263 pub size: Option<usize>,
264 /// Last commit made to the tree/blob
265 pub last_commit: Option<Commit>,
266 }
267
268 impl RepositoryTreeEntry {
269 // I love you Emilia <3
270 pub fn new(id: &str, name: &str, object_type: RepositoryObjectType, mode: i32) -> Self {
271 Self {
272 id: id.to_string(),
273 name: name.to_string(),
274 object_type,
275 mode,
276 size: None,
277 last_commit: None,
278 }
279 }
280 }
281
282 #[derive(Debug, Clone, Serialize, Deserialize)]
283 pub struct RepositoryTreeEntryWithCommit {
284 pub tree_entry: RepositoryTreeEntry,
285 pub commit: Commit,
286 }
287
288 /// Info about a git commit
289 #[derive(PartialEq, Hash, Eq, Debug, Clone, Serialize, Deserialize)]
290 pub struct Commit {
291 /// Unique commit ID
292 pub oid: String,
293 /// Shortened abbreviated OID
294 /// This starts at the git config's "core.abbrev" length (default 7 characters) and
295 /// iteratively extends to a longer string if that length is ambiguous. The
296 /// result will be unambiguous (at least until new objects are added to the repository).
297 pub short_oid: String,
298 /// First paragraph of the full message
299 pub summary: Option<String>,
300 /// Everything in the full message apart from the first paragraph
301 pub body: Option<String>,
302 /// All commit id's of the parents of this commit
303 pub parents: Vec<String>,
304 /// Who created the commit
305 pub author: CommitSignature,
306 /// Who committed the commit
307 pub committer: CommitSignature,
308 /// Time when the commit happened
309 pub time: chrono::NaiveDateTime,
310 }
311
312 /// Gets all info from [`git2::Commit`] for easy use
313 impl From<git2::Commit<'_>> for Commit {
314 fn from(commit: git2::Commit<'_>) -> Self {
315 Self {
316 oid: commit.id().to_string(),
317 // This shouldn't ever fail, as we already know the object has an oid.
318 short_oid: commit
319 .as_object()
320 .short_id()
321 .unwrap()
322 .as_str()
323 .unwrap()
324 .to_string(),
325 summary: commit.summary().map(|summary| summary.to_string()),
326 body: commit.body().map(|body| body.to_string()),
327 parents: commit.parents().map(|parent| parent.id().to_string()).collect::<Vec<String>>(),
328 author: commit.author().into(),
329 committer: commit.committer().into(),
330 time: chrono::NaiveDateTime::from_timestamp_opt(commit.time().seconds(), 0).unwrap(),
331 }
332 }
333 }
334
335 /// Git commit signature
336 #[derive(PartialEq, Hash, Eq, Debug, Clone, Serialize, Deserialize)]
337 pub struct CommitSignature {
338 pub name: Option<String>,
339 pub email: Option<String>,
340 pub time: chrono::NaiveDateTime,
341 }
342
343 /// Converts the signature from git2 into something usable without explicit lifetimes.
344 impl From<git2::Signature<'_>> for CommitSignature {
345 fn from(signature: git2::Signature<'_>) -> Self {
346 Self {
347 name: signature.name().map(|name| name.to_string()),
348 email: signature.email().map(|email| email.to_string()),
349 time: chrono::NaiveDateTime::from_timestamp_opt(signature.when().seconds(), 0).unwrap(),
350 }
351 }
352 }
353
354 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
355 pub struct RepositorySummary {
356 pub repository: Repository,
357 pub owner: User,
358 pub visibility: RepositoryVisibility,
359 pub description: Option<String>,
360 pub last_commit: Option<Commit>,
361 }
362
363 #[derive(Clone, Debug, Serialize, Deserialize)]
364 pub struct IssueLabel {
365 pub name: String,
366 pub color: String,
367 }
368
369 #[derive(Clone, Debug, Serialize, Deserialize)]
370 pub struct RepositoryIssue {
371 pub author: User,
372 pub id: u64,
373 pub title: String,
374 pub contents: String,
375 pub labels: Vec<IssueLabel>,
376 }
377