forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.7 MiBb00f3f4Tahinli1 month ago147 commits

issues.rs375 lines, 10.9 KiBHistoryRawDownload
1//! Issue, comment, label and milestone types, and their validation. Stored shapes are in
2//! migrations/0004_issues.sql; the store functions live in store/issues.rs and store/labels.rs.
3
4use crate::error::{Error, Result};
5use crate::model::Id;
6
7/// Longest accepted issue title, in characters.
8pub const MAX_TITLE: usize = 256;
9/// Largest accepted issue, comment or edit body, in bytes.
10pub const MAX_BODY: usize = 65536;
11/// Longest accepted label name, in characters.
12pub const MAX_LABEL_NAME: usize = 50;
13/// Most assignees one issue can have.
14pub const MAX_ASSIGNEES: usize = 10;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum IssueState {
18 Open,
19 Closed,
20}
21
22impl IssueState {
23 pub fn as_str(&self) -> &'static str {
24 match self {
25 IssueState::Open => "open",
26 IssueState::Closed => "closed",
27 }
28 }
29}
30
31impl std::str::FromStr for IssueState {
32 type Err = Error;
33
34 fn from_str(s: &str) -> Result<Self> {
35 match s {
36 "open" => Ok(IssueState::Open),
37 "closed" => Ok(IssueState::Closed),
38 other => Err(Error::Invalid(format!("issue state {other:?}"))),
39 }
40 }
41}
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum StateReason {
45 Completed,
46 NotPlanned,
47}
48
49impl StateReason {
50 pub fn as_str(&self) -> &'static str {
51 match self {
52 StateReason::Completed => "completed",
53 StateReason::NotPlanned => "not_planned",
54 }
55 }
56}
57
58impl std::str::FromStr for StateReason {
59 type Err = Error;
60
61 fn from_str(s: &str) -> Result<Self> {
62 match s {
63 "completed" => Ok(StateReason::Completed),
64 "not_planned" => Ok(StateReason::NotPlanned),
65 other => Err(Error::Invalid(format!("state reason {other:?}"))),
66 }
67 }
68}
69
70#[derive(Debug, Clone, PartialEq)]
71pub struct Issue {
72 pub id: Id,
73 pub repo_id: Id,
74 pub number: i64,
75 pub title: String,
76 pub body: String,
77 pub state: IssueState,
78 pub state_reason: Option<StateReason>,
79 pub author_id: Id,
80 pub milestone_id: Option<Id>,
81 pub comment_count: i64,
82 pub created_at: String,
83 pub updated_at: String,
84 pub closed_at: Option<String>,
85 /// Locked conversations accept writes only from collaborators with Triage or higher.
86 pub locked: bool,
87 /// One of `LOCK_REASONS`, or `None` when no reason was given.
88 pub lock_reason: Option<String>,
89}
90
91/// Reasons accepted when locking a conversation.
92pub const LOCK_REASONS: &[&str] = &["off_topic", "too_heated", "resolved", "spam"];
93
94#[derive(Debug, Clone, PartialEq)]
95pub struct Comment {
96 pub id: Id,
97 pub issue_id: Id,
98 pub author_id: Id,
99 pub body: String,
100 pub created_at: String,
101 pub updated_at: String,
102 pub edited: bool,
103}
104
105#[derive(Debug, Clone, PartialEq)]
106pub struct IssueEvent {
107 pub id: Id,
108 pub issue_id: Id,
109 /// `None` for system events.
110 pub actor_id: Option<Id>,
111 pub kind: String,
112 pub data: serde_json::Value,
113 pub created_at: String,
114}
115
116#[derive(Debug, Clone, PartialEq)]
117pub struct Label {
118 pub id: Id,
119 pub repo_id: Id,
120 pub name: String,
121 /// Lowercase `#rrggbb`.
122 pub color: String,
123 pub description: String,
124}
125
126#[derive(Debug, Clone, PartialEq)]
127pub struct Milestone {
128 pub id: Id,
129 pub repo_id: Id,
130 pub title: String,
131 pub description: String,
132 /// `YYYY-MM-DD` or `None`.
133 pub due_on: Option<String>,
134 pub state: IssueState,
135 pub created_at: String,
136 pub closed_at: Option<String>,
137 /// Counts filled by list/get queries.
138 pub open_issues: i64,
139 pub closed_issues: i64,
140}
141
142#[derive(Debug, Clone, PartialEq)]
143pub struct IssueFilter {
144 pub state: Option<IssueState>,
145 /// Label name.
146 pub label: Option<String>,
147 /// Milestone title.
148 pub milestone: Option<String>,
149 /// Author username.
150 pub author: Option<String>,
151 /// Assignee username.
152 pub assignee: Option<String>,
153 /// Username with a pending review request (pull requests only).
154 pub review_requested: Option<String>,
155 /// Substring of the title, case-insensitive.
156 pub query: Option<String>,
157 /// Pull requests only: `Some(true)` lists drafts, `Some(false)` lists ready pull requests.
158 pub draft: Option<bool>,
159 pub sort: IssueSort,
160 /// 1-based.
161 pub page: u32,
162 pub per_page: u32,
163}
164
165impl Default for IssueFilter {
166 fn default() -> Self {
167 IssueFilter {
168 state: Some(IssueState::Open),
169 label: None,
170 milestone: None,
171 author: None,
172 assignee: None,
173 review_requested: None,
174 query: None,
175 draft: None,
176 sort: IssueSort::Newest,
177 page: 1,
178 per_page: 25,
179 }
180 }
181}
182
183#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
184pub enum IssueSort {
185 #[default]
186 Newest,
187 Oldest,
188 RecentlyUpdated,
189}
190
191impl IssueSort {
192 /// The value used in the `sort` query parameter.
193 pub fn as_str(&self) -> &'static str {
194 match self {
195 IssueSort::Newest => "newest",
196 IssueSort::Oldest => "oldest",
197 IssueSort::RecentlyUpdated => "updated",
198 }
199 }
200}
201
202impl std::str::FromStr for IssueSort {
203 type Err = Error;
204
205 fn from_str(s: &str) -> Result<Self> {
206 match s {
207 "newest" => Ok(IssueSort::Newest),
208 "oldest" => Ok(IssueSort::Oldest),
209 "updated" => Ok(IssueSort::RecentlyUpdated),
210 other => Err(Error::Invalid(format!("sort {other:?}"))),
211 }
212 }
213}
214
215#[derive(Debug, Clone, PartialEq)]
216pub struct IssueListItem {
217 pub issue: Issue,
218 /// Display username of the author.
219 pub author: String,
220 pub labels: Vec<Label>,
221 /// Display usernames of the assignees.
222 pub assignees: Vec<String>,
223}
224
225/// Trimmed title: non-empty, at most `MAX_TITLE` characters, no control characters.
226pub fn validate_title(t: &str) -> Result<String> {
227 let title = t.trim();
228 if title.is_empty() {
229 return Err(Error::Invalid("title is empty".into()));
230 }
231 if title.chars().count() > MAX_TITLE {
232 return Err(Error::Invalid(format!(
233 "title is longer than {MAX_TITLE} characters"
234 )));
235 }
236 if title.chars().any(char::is_control) {
237 return Err(Error::Invalid("title contains control characters".into()));
238 }
239 Ok(title.to_string())
240}
241
242/// Body: at most `MAX_BODY` bytes. An empty body is allowed.
243pub fn validate_body(b: &str) -> Result<()> {
244 if b.len() > MAX_BODY {
245 return Err(Error::Invalid(format!(
246 "body is longer than {MAX_BODY} bytes"
247 )));
248 }
249 Ok(())
250}
251
252/// Returns `(trimmed name, normalized color)`. The name is 1..=50 characters with no control
253/// characters. The color is `#rgb` or `#rrggbb` in any case and comes back as lowercase `#rrggbb`.
254pub fn validate_label(name: &str, color: &str) -> Result<(String, String)> {
255 let name = name.trim();
256 let len = name.chars().count();
257 if len == 0 || len > MAX_LABEL_NAME {
258 return Err(Error::Invalid(format!(
259 "label name must be 1 to {MAX_LABEL_NAME} characters"
260 )));
261 }
262 if name.chars().any(char::is_control) {
263 return Err(Error::Invalid(
264 "label name contains control characters".into(),
265 ));
266 }
267 let color = normalize_color(color)
268 .ok_or_else(|| Error::Invalid(format!("label color {color:?} is not #rgb or #rrggbb")))?;
269 Ok((name.to_string(), color))
270}
271
272fn normalize_color(color: &str) -> Option<String> {
273 let hex = color.strip_prefix('#')?;
274 if !hex.chars().all(|c| c.is_ascii_hexdigit()) {
275 return None;
276 }
277 let lower = hex.to_ascii_lowercase();
278 match lower.len() {
279 3 => {
280 let mut out = String::with_capacity(7);
281 out.push('#');
282 for c in lower.chars() {
283 out.push(c);
284 out.push(c);
285 }
286 Some(out)
287 }
288 6 => Some(format!("#{lower}")),
289 _ => None,
290 }
291}
292
293#[cfg(test)]
294mod tests {
295 use super::*;
296
297 #[test]
298 fn title_is_trimmed_and_checked() {
299 assert_eq!(validate_title(" Fix it ").unwrap(), "Fix it");
300 assert!(validate_title(" ").is_err());
301 assert!(validate_title("").is_err());
302 assert!(validate_title("a\tb").is_err());
303 assert!(validate_title("a\nb").is_err());
304 assert!(validate_title(&"x".repeat(MAX_TITLE)).is_ok());
305 assert!(validate_title(&"x".repeat(MAX_TITLE + 1)).is_err());
306 // Counted in characters, not bytes.
307 assert!(validate_title(&"é".repeat(MAX_TITLE)).is_ok());
308 assert!(validate_title(&"é".repeat(MAX_TITLE + 1)).is_err());
309 }
310
311 #[test]
312 fn body_is_checked_in_bytes() {
313 assert!(validate_body("").is_ok());
314 assert!(validate_body(&"x".repeat(MAX_BODY)).is_ok());
315 assert!(validate_body(&"x".repeat(MAX_BODY + 1)).is_err());
316 // 2 bytes per char: 32768 chars is exactly MAX_BODY bytes.
317 assert!(validate_body(&"é".repeat(MAX_BODY / 2)).is_ok());
318 assert!(validate_body(&"é".repeat(MAX_BODY / 2 + 1)).is_err());
319 }
320
321 #[test]
322 fn label_name_and_color_are_normalized() {
323 assert_eq!(
324 validate_label(" bug ", "#FF0000").unwrap(),
325 ("bug".to_string(), "#ff0000".to_string())
326 );
327 assert_eq!(
328 validate_label("x", "#AbC").unwrap(),
329 ("x".to_string(), "#aabbcc".to_string())
330 );
331 assert!(validate_label("", "#fff").is_err());
332 assert!(validate_label(" ", "#fff").is_err());
333 assert!(validate_label(&"a".repeat(MAX_LABEL_NAME), "#fff").is_ok());
334 assert!(validate_label(&"a".repeat(MAX_LABEL_NAME + 1), "#fff").is_err());
335 assert!(validate_label("a\u{7}", "#fff").is_err());
336 }
337
338 #[test]
339 fn label_color_must_be_hex() {
340 for bad in [
341 "", "fff", "#ff", "#ffff", "#fffffff", "#gggggg", "red", "# fff", "#ff00 0",
342 ] {
343 assert!(validate_label("x", bad).is_err(), "{bad:?} accepted");
344 }
345 }
346
347 #[test]
348 fn enums_round_trip() {
349 for s in [IssueState::Open, IssueState::Closed] {
350 assert_eq!(s.as_str().parse::<IssueState>().ok(), Some(s));
351 }
352 assert!("Open".parse::<IssueState>().is_err());
353 for r in [StateReason::Completed, StateReason::NotPlanned] {
354 assert_eq!(r.as_str().parse::<StateReason>().ok(), Some(r));
355 }
356 assert!("duplicate".parse::<StateReason>().is_err());
357 for s in [
358 IssueSort::Newest,
359 IssueSort::Oldest,
360 IssueSort::RecentlyUpdated,
361 ] {
362 assert_eq!(s.as_str().parse::<IssueSort>().ok(), Some(s));
363 }
364 assert!("bogus".parse::<IssueSort>().is_err());
365 }
366
367 #[test]
368 fn default_filter_is_open_first_page() {
369 let f = IssueFilter::default();
370 assert_eq!(f.state, Some(IssueState::Open));
371 assert_eq!(f.page, 1);
372 assert_eq!(f.per_page, 25);
373 assert_eq!(f.sort, IssueSort::Newest);
374 }
375}