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

ambee/giterated

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

The long awaited, exhalted huge networking stack change.

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨21b6a72

⁨giterated-models/src/repository/mod.rs⁩ - ⁨13736⁩ 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 fn home_uri(&self) -> String {
68 self.instance.home_uri()
69 }
70 }
71
72 impl TryFrom<String> for Repository {
73 type Error = RepositoryParseError;
74
75 fn try_from(value: String) -> Result<Self, Self::Error> {
76 Self::from_str(&value)
77 }
78 }
79
80 impl FromStr for Repository {
81 type Err = RepositoryParseError;
82
83 fn from_str(s: &str) -> Result<Self, Self::Err> {
84 let mut by_ampersand = s.split('@');
85 let mut path_split = by_ampersand.next().ok_or(RepositoryParseError)?.split('/');
86
87 let instance = Instance::from_str(by_ampersand.next().ok_or(RepositoryParseError)?)
88 .map_err(|_| RepositoryParseError)?;
89 let owner = User::from_str(path_split.next().ok_or(RepositoryParseError)?)
90 .map_err(|_| RepositoryParseError)?;
91 let name = path_split.next().ok_or(RepositoryParseError)?.to_string();
92
93 Ok(Self {
94 instance,
95 owner,
96 name,
97 })
98 }
99 }
100
101 #[derive(Debug, thiserror::Error)]
102 #[error("no parse!")]
103 pub struct RepositoryParseError;
104
105 /// Visibility of the repository to the general eye
106 #[derive(PartialEq, Eq, Debug, Hash, Serialize, Deserialize, Clone, sqlx::Type)]
107 #[sqlx(type_name = "visibility", rename_all = "lowercase")]
108 pub enum RepositoryVisibility {
109 Public,
110 Unlisted,
111 Private,
112 }
113
114 /// Implements [`Display`] for [`RepositoryVisiblity`] using [`Debug`]
115 impl Display for RepositoryVisibility {
116 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
117 write!(f, "{:?}", self)
118 }
119 }
120
121 #[derive(Clone, Debug, Serialize, Deserialize)]
122 pub struct RepositoryView {
123 /// Name of the repository
124 ///
125 /// This is different than the [`Repository`] name,
126 /// which may be a path.
127 pub name: String,
128 /// Owner of the Repository
129 pub owner: User,
130 /// Repository description
131 pub description: Option<Description>,
132 /// Repository visibility
133 pub visibility: Visibility,
134 /// Default branch of the repository
135 pub default_branch: DefaultBranch,
136 /// Last commit made to the repository
137 pub latest_commit: Option<LatestCommit>,
138 /// Repository statistics
139 pub stats: RepositoryStatistics,
140 /// Revision of the displayed tree
141 pub tree_rev: Option<String>,
142 /// Repository tree
143 pub tree: Vec<RepositoryTreeEntry>,
144 }
145
146 /// Generic repository statistics
147 #[derive(Clone, Debug, Serialize, Deserialize)]
148 pub struct RepositoryStatistics {
149 /// Amount of commits made to this branch in the repository
150 pub commits: usize,
151 /// Amount of branches the repository has
152 pub branches: usize,
153 /// Amount of tags the repository has
154 pub tags: usize,
155 }
156
157 /// Repository branch
158 #[derive(Clone, Debug, Serialize, Deserialize)]
159 pub struct RepositoryBranch {
160 /// Full reference name
161 pub name: String,
162 /// Whether the repository is stale or not
163 pub stale: bool,
164 /// The last commit made to the branch
165 pub last_commit: Option<Commit>,
166 }
167
168 #[derive(Clone, Debug, Serialize, Deserialize)]
169 pub struct RepositoryFile {
170 /// ID of the file
171 pub id: String,
172 /// Content of the file
173 pub content: Vec<u8>,
174 /// If the file is binary or not
175 pub binary: bool,
176 /// File size in bytes
177 pub size: usize,
178 }
179
180 #[derive(Clone, Debug, Serialize, Deserialize)]
181 pub struct RepositoryDiff {
182 /// "to" side of the diff commit
183 pub new_commit: Commit,
184 /// Total number of files changed
185 pub files_changed: usize,
186 /// Total number of insertions
187 pub insertions: usize,
188 /// Total number of deletions
189 pub deletions: usize,
190 /// List of changed files
191 pub files: Vec<RepositoryDiffFile>,
192 }
193
194 /// Represents the type of change made to a [`RepositoryDiffFile`]
195 #[derive(Clone, Debug, Serialize, Deserialize)]
196 pub enum RepositoryDiffFileStatus {
197 /// No changes
198 Unmodified,
199 Added,
200 Deleted,
201 /// Content changed between old and new
202 Modified,
203 /// Renamed between old and new
204 Renamed,
205 /// Copied from another old entry
206 Copied,
207 /// Ignored item in workdir
208 Ignored,
209 /// Untracked item in workdir
210 Untracked,
211 /// Type of file changed between old and new
212 Typechange,
213 /// File is unreadable
214 Unreadable,
215 /// File in the index is conflicted
216 Conflicted,
217 }
218
219 impl From<git2::Delta> for RepositoryDiffFileStatus {
220 fn from(status: git2::Delta) -> Self {
221 match status {
222 git2::Delta::Unmodified => Self::Unmodified,
223 git2::Delta::Added => Self::Added,
224 git2::Delta::Deleted => Self::Deleted,
225 git2::Delta::Modified => Self::Modified,
226 git2::Delta::Renamed => Self::Renamed,
227 git2::Delta::Copied => Self::Copied,
228 git2::Delta::Ignored => Self::Ignored,
229 git2::Delta::Untracked => Self::Untracked,
230 git2::Delta::Typechange => Self::Typechange,
231 git2::Delta::Unreadable => Self::Unreadable,
232 git2::Delta::Conflicted => Self::Conflicted,
233 }
234 }
235 }
236
237 /// Represents a single file of a diff
238 #[derive(Clone, Debug, Serialize, Deserialize)]
239 pub struct RepositoryDiffFile {
240 /// The type of change made to this file
241 pub status: RepositoryDiffFileStatus,
242 /// "From" side of the diff, can be nonexistent if file for example got added for the first time
243 pub old_file_info: Option<RepositoryDiffFileInfo>,
244 /// "To" side of the diff, can be nonexistent if file got removed
245 pub new_file_info: Option<RepositoryDiffFileInfo>,
246 /// Individual chunks of changes in this file
247 pub chunks: Vec<RepositoryDiffFileChunk>,
248 }
249
250 /// Represents one side of a file diff [`RepositoryDiffFile`]
251 #[derive(Clone, Debug, Serialize, Deserialize)]
252 pub struct RepositoryDiffFileInfo {
253 /// ID of the file
254 pub id: String,
255 /// Path of the entry relative to the working directory of the repository
256 pub path: String,
257 /// Size in bytes
258 pub size: u64,
259 /// If the file is binary or not
260 pub binary: bool,
261 }
262
263 /// Represents a single chunk of a file diff [`RepositoryDiffFile`]
264 #[derive(Clone, Debug, Serialize, Deserialize)]
265 pub struct RepositoryDiffFileChunk {
266 /// Header of the chunk
267 pub header: Option<String>,
268 /// Starting line number of the old file
269 pub old_start: u32,
270 /// Number of lines in "from" side of this chunk
271 pub old_lines: u32,
272 /// Starting line number of the new file
273 pub new_start: u32,
274 /// Number of lines in "to" side of this chunk
275 pub new_lines: u32,
276 /// Lines of the chunk
277 pub lines: Vec<RepositoryChunkLine>,
278 }
279
280 /// Represents the change type of the [`RepositoryChunkLine`], incomplete of what git actually provides.
281 #[derive(Clone, Debug, Serialize, Deserialize)]
282 pub enum RepositoryChunkLineType {
283 Context,
284 Addition,
285 Deletion,
286 }
287
288 impl From<git2::DiffLineType> for RepositoryChunkLineType {
289 fn from(line_type: git2::DiffLineType) -> Self {
290 match line_type {
291 git2::DiffLineType::Context => Self::Context,
292 git2::DiffLineType::Addition => Self::Addition,
293 git2::DiffLineType::Deletion => Self::Deletion,
294 _ => Self::Context,
295 }
296 }
297 }
298
299 /// Represents a single line of a [`RepositoryDiffFileChunk`]
300 #[derive(Clone, Debug, Serialize, Deserialize)]
301 pub struct RepositoryChunkLine {
302 /// Type of change the line is
303 pub change_type: RepositoryChunkLineType,
304 /// Content of the line
305 pub content: String,
306 /// Line number in old file
307 pub old_line_num: Option<u32>,
308 /// Line number in new file
309 pub new_line_num: Option<u32>,
310 }
311
312 #[derive(Debug, Clone, Serialize, Deserialize)]
313 pub enum RepositoryObjectType {
314 Tree,
315 Blob,
316 }
317
318 /// Stored info for our tree entries
319 #[derive(Debug, Clone, Serialize, Deserialize)]
320 pub struct RepositoryTreeEntry {
321 /// ID of the tree/blob
322 pub id: String,
323 /// Name of the tree/blob
324 pub name: String,
325 /// Type of the tree entry
326 pub object_type: RepositoryObjectType,
327 /// Git supplies us with the mode at all times, and people like it displayed.
328 pub mode: i32,
329 /// File size
330 pub size: Option<usize>,
331 /// Last commit made to the tree/blob
332 pub last_commit: Option<Commit>,
333 }
334
335 impl RepositoryTreeEntry {
336 // I love you Emilia <3
337 pub fn new(id: &str, name: &str, object_type: RepositoryObjectType, mode: i32) -> Self {
338 Self {
339 id: id.to_string(),
340 name: name.to_string(),
341 object_type,
342 mode,
343 size: None,
344 last_commit: None,
345 }
346 }
347 }
348
349 #[derive(Debug, Clone, Serialize, Deserialize)]
350 pub struct RepositoryTreeEntryWithCommit {
351 pub tree_entry: RepositoryTreeEntry,
352 pub commit: Commit,
353 }
354
355 /// Info about a git commit
356 #[derive(PartialEq, Hash, Eq, Debug, Clone, Serialize, Deserialize)]
357 pub struct Commit {
358 /// Unique commit ID
359 pub oid: String,
360 /// Shortened abbreviated OID
361 /// This starts at the git config's "core.abbrev" length (default 7 characters) and
362 /// iteratively extends to a longer string if that length is ambiguous. The
363 /// result will be unambiguous (at least until new objects are added to the repository).
364 pub short_oid: String,
365 /// First paragraph of the full message
366 pub summary: Option<String>,
367 /// Everything in the full message apart from the first paragraph
368 pub body: Option<String>,
369 /// All commit id's of the parents of this commit
370 pub parents: Vec<String>,
371 /// Who created the commit
372 pub author: CommitSignature,
373 /// Who committed the commit
374 pub committer: CommitSignature,
375 /// Time when the commit happened
376 pub time: chrono::NaiveDateTime,
377 }
378
379 /// Gets all info from [`git2::Commit`] for easy use
380 impl From<git2::Commit<'_>> for Commit {
381 fn from(commit: git2::Commit<'_>) -> Self {
382 Self {
383 oid: commit.id().to_string(),
384 // This shouldn't ever fail, as we already know the object has an oid.
385 short_oid: commit
386 .as_object()
387 .short_id()
388 .unwrap()
389 .as_str()
390 .unwrap()
391 .to_string(),
392 summary: commit.summary().map(|summary| summary.to_string()),
393 body: commit.body().map(|body| body.to_string()),
394 parents: commit
395 .parents()
396 .map(|parent| parent.id().to_string())
397 .collect::<Vec<String>>(),
398 author: commit.author().into(),
399 committer: commit.committer().into(),
400 time: chrono::NaiveDateTime::from_timestamp_opt(commit.time().seconds(), 0).unwrap(),
401 }
402 }
403 }
404
405 /// Git commit signature
406 #[derive(PartialEq, Hash, Eq, Debug, Clone, Serialize, Deserialize)]
407 pub struct CommitSignature {
408 pub name: Option<String>,
409 pub email: Option<String>,
410 pub time: chrono::NaiveDateTime,
411 }
412
413 /// Converts the signature from git2 into something usable without explicit lifetimes.
414 impl From<git2::Signature<'_>> for CommitSignature {
415 fn from(signature: git2::Signature<'_>) -> Self {
416 Self {
417 name: signature.name().map(|name| name.to_string()),
418 email: signature.email().map(|email| email.to_string()),
419 time: chrono::NaiveDateTime::from_timestamp_opt(signature.when().seconds(), 0).unwrap(),
420 }
421 }
422 }
423
424 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
425 pub struct RepositorySummary {
426 pub repository: Repository,
427 pub owner: User,
428 pub visibility: RepositoryVisibility,
429 pub description: Option<String>,
430 pub last_commit: Option<Commit>,
431 }
432
433 #[derive(Clone, Debug, Serialize, Deserialize)]
434 pub struct IssueLabel {
435 pub name: String,
436 pub color: String,
437 }
438
439 #[derive(Clone, Debug, Serialize, Deserialize)]
440 pub struct RepositoryIssue {
441 pub author: User,
442 pub id: u64,
443 pub title: String,
444 pub contents: String,
445 pub labels: Vec<IssueLabel>,
446 }
447