summary refs log tree commit diff stats
path: root/pkgs/by-name/ba/back/src/issues/issue/mod.rs
blob: b78f47377a00be4d56401ef98c1c5b53f979219f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
// Back - An extremely simple git issue tracking system. Inspired by tvix's
// panettone
//
// Copyright (C) 2024 Benedikt Peetz <benedikt.peetz@b-peetz.de>
// SPDX-License-Identifier: AGPL-3.0-or-later
//
// This file is part of Back.
//
// You should have received a copy of the License along with this program.
// If not, see <https://www.gnu.org/licenses/agpl.txt>.

use std::fmt::Display;

use chrono::DateTime;
use gix::{bstr::ByteSlice, Commit, Id, ObjectId, Repository};
use raw::{Operation, RawIssue};
use rocket::response::content::RawHtml;

use crate::SOURCE_CODE_REPOSITORY;

use super::format::{BackString, Markdown};

mod raw;

#[derive(Debug, Default)]
pub struct TimeStamp {
    value: u64,
}
impl TimeStamp {
    pub fn new(val: u64) -> Self {
        Self { value: val }
    }
}
impl Display for TimeStamp {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let date =
            DateTime::from_timestamp(self.value as i64, 0).expect("This timestamp should be vaild");

        let newdate = date.format("%Y-%m-%d %H:%M:%S");
        f.write_str(newdate.to_string().as_str())
    }
}

#[derive(Debug)]
pub struct Comment<'a> {
    pub id: Id<'a>,
    pub author: Author,
    pub message: Markdown,
    pub timestamp: TimeStamp,
}

#[derive(Debug, Default)]
pub struct Author {
    name: BackString,
    email: BackString,
}

#[derive(Debug)]
pub struct IssueId<'a> {
    value: Id<'a>,
}
impl<'a> IssueId<'a> {
    pub fn new(id: Id<'a>) -> Self {
        Self { value: id }
    }
}
impl Display for IssueId<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let shortend = self.value.shorten().expect("This should work.");
        f.write_str(shortend.to_string().as_str())
    }
}

#[derive(Default, Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
pub enum Status {
    #[default]
    Open,
    Closed,
}
impl Display for Status {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Status::Open => f.write_str("Open"),
            Status::Closed => f.write_str("Closed"),
        }
    }
}

#[derive(Debug)]
pub struct Issue<'a> {
    pub id: IssueId<'a>,
    pub author: Author,
    pub timestamp: TimeStamp,
    pub title: Markdown,
    pub message: Markdown,
    pub comments: Vec<Comment<'a>>,
    pub status: Status,
    pub last_status_change: Option<TimeStamp>,
}
impl<'a> Issue<'a> {
    pub fn default_with_id(id: Id<'a>) -> Self {
        Self {
            id: IssueId::new(id),
            author: Author::default(),
            timestamp: TimeStamp::default(),
            title: Markdown::default(),
            message: Markdown::default(),
            comments: <Vec<Comment>>::default(),
            status: Status::default(),
            last_status_change: <Option<TimeStamp>>::default(),
        }
    }

    pub fn from_commit_id(repo: &'a Repository, commit_id: ObjectId) -> Self {
        fn unwrap_id<'b>(repo: &Repository, id: &Commit<'b>) -> (RawIssue, Id<'b>) {
            let tree_obj = repo
                .find_object(id.tree_id().unwrap())
                .expect("The object with this id should exist.")
                .try_into_tree()
                .expect("The git-bug's data model enforces this.");

            let ops_ref = tree_obj.find_entry("ops").unwrap();

            let issue_data = repo
                .find_object(ops_ref.object_id())
                .expect("The object with this id should exist.")
                .try_into_blob()
                .expect("The git-bug's data model enforces this.")
                .data
                .clone();

            let raw_issue = serde_json::from_str(
                issue_data
                    .to_str()
                    .expect("git-bug's ensures, that this is valid json."),
            )
            .expect("The returned json should be valid");

            (raw_issue, id.id())
        }

        let commit_obj = repo
            .find_object(commit_id)
            .expect("The object with this id should exist.")
            .try_into_commit()
            .expect("The git-bug's data model enforces this.");

        let mut issues = vec![unwrap_id(repo, &commit_obj)];

        let mut current_commit_obj = commit_obj;
        while current_commit_obj.parent_ids().count() != 0 {
            assert_eq!(
                current_commit_obj.parent_ids().count(),
                1,
                "There should be only one parent"
            );
            let parent = current_commit_obj
                .parent_ids()
                .last()
                .expect("One does exist");

            let parent_id = parent.object().expect("The object exists").id;
            let parent_commit = repo
                .find_object(parent_id)
                .expect("This is a valid id")
                .try_into_commit()
                .expect("This should be a commit");

            issues.push(unwrap_id(repo, &parent_commit));
            current_commit_obj = parent_commit;
        }

        let mut final_issue = Self::default_with_id(current_commit_obj.id());
        for (issue, id) in issues {
            for op in issue.operations {
                match op {
                    Operation::AddComment { timestamp, message } => {
                        final_issue.comments.push(Comment {
                            id,
                            author: issue.author.load_identity(repo),
                            message: Markdown::from(message),
                            timestamp: TimeStamp::new(timestamp),
                        })
                    }
                    Operation::Create {
                        timestamp,
                        title,
                        message,
                    } => {
                        final_issue.author = issue.author.load_identity(repo);
                        final_issue.title = Markdown::from(title);
                        final_issue.message = Markdown::from(message);
                        final_issue.timestamp = TimeStamp::new(timestamp);
                    }
                    Operation::SetStatus { timestamp, status } => {
                        final_issue.status = status;
                        final_issue.last_status_change = Some(TimeStamp::new(timestamp));
                    }
                }
            }
        }
        final_issue
    }

    pub fn to_list_entry(&self) -> RawHtml<String> {
        let comment_list = if self.comments.is_empty() {
            String::new()
        } else {
            format!(
                r#"
                <span class="comment-count"> - {} comments</span>
            "#,
                self.comments.len()
            )
        };
        let Issue {
            id,
            title,
            message: _,
            author,
            timestamp,
            comments: _,
            status: _,
            last_status_change: _,
        } = self;
        let Author { name, email } = author;
        RawHtml(format!(
            r#"
               <li>
                  <a href="/issue/{id}">
                     <p>
                        <span class="issue-subject">{title}</span>
                     </p>
                     <span class="issue-number">{id}</span> - <span class="created-by-at">Opened by <span class="user-name">{name}</span> <span class="user-email">&lt;{email}&gt;</span> at <span class="timestamp">{timestamp}</span></span>{comment_list}                  </a>
               </li>
"#,
        ))
    }

    pub fn to_html(&self) -> RawHtml<String> {
        let fmt_comments: String = self
            .comments
            .iter()
            .map(|val| {
                let Comment {
                    id,
                    author,
                    message,
                    timestamp,
                } = val;
                let Author { name, email: _ } = author;

                format!(
                    r#"
               <li class="comment" id="{id}">
                  {message}
                  <p class="comment-info"><span class="user-name">{name} at {timestamp}</span></p>
               </li>
                "#,
                )
            })
            .collect::<Vec<String>>()
            .join("\n");

        let maybe_comments = if fmt_comments.is_empty() {
            String::new()
        } else {
            format!(
                r#"
            <ol class="issue-history">
            {fmt_comments}
            </ol>
            "#
            )
        };

        {
            let Issue {
                id,
                title,
                message,
                author,
                timestamp,
                comments: _,
                status: _,
                last_status_change: _,
            } = self;
            let Author { name, email } = author;
            let html_title = BackString::from(title.clone());

            RawHtml(format!(
                r#"
<!DOCTYPE html>
<html lang="en">
   <head>
      <title>{html_title} | Back</title>
      <link href="/style.css" rel="stylesheet" type="text/css">
      <meta content="width=device-width,initial-scale=1" name="viewport">
   </head>
   <body>
      <div class="content">
         <nav>
         <a href="/issues/open">Open Issues</a>
         <a href="/issues/closed">Closed Issues</a>
         </nav>
         <header>
            <h1>{title}</h1>
            <div class="issue-number">{id}</div>
         </header>
         <main>
            <div class="issue-info">
                <span class="created-by-at">Opened by <span class="user-name">{name}</span> <span class="user-email">&lt;{email}&gt;</span> at <span class="timestamp">{timestamp}</span></span>
            </div>
            {message}
            {maybe_comments}
         </main>
         <footer>
            <nav>
            <a href="/issues/open">Open Issues</a>
            <a href="{}">Source code</a>
            <a href="/issues/closed">Closed Issues</a>
            </nav>
         </footer>
      </div>
   </body>
</html>
"#,
                SOURCE_CODE_REPOSITORY.get().expect("This should be set")
            ))
        }
    }
}