gitea-sdk-rs 0.1.0

Rust SDK for the Gitea API
Documentation
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
// Copyright 2026 infinitete. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

//! Request option types for pull request API endpoints.

use crate::pagination::{ListOptions, QueryEncode};
use crate::types::enums::{MergeStyle, ReviewStateType, StateType};
use crate::{Deserialize, Serialize};

// ── pull.go ─────────────────────────────────────────────────────

/// ListPullRequestsOptions options for listing pull requests
#[derive(Debug, Clone)]
/// Options for List Pull Requests Option.
pub struct ListPullRequestsOptions {
    pub list_options: ListOptions,
    pub state: StateType,
    /// oldest, recentupdate, leastupdate, mostcomment, leastcomment, priority
    pub sort: String,
    pub milestone: i64,
}

impl Default for ListPullRequestsOptions {
    fn default() -> Self {
        Self {
            list_options: ListOptions::default(),
            state: StateType::All,
            sort: String::new(),
            milestone: 0,
        }
    }
}

impl QueryEncode for ListPullRequestsOptions {
    fn query_encode(&self) -> String {
        let mut out = self.list_options.query_encode();
        if !matches!(self.state, StateType::All) {
            out.push_str(&format!("&state={}", self.state));
        }
        if !self.sort.is_empty() {
            out.push_str(&format!("&sort={}", self.sort));
        }
        if self.milestone > 0 {
            out.push_str(&format!("&milestone={}", self.milestone));
        }
        out
    }
}

/// CreatePullRequestOption options when creating a pull request
#[derive(Debug, Clone, Serialize, Deserialize)]
/// Options for Create Pull Request Option.
pub struct CreatePullRequestOption {
    pub head: String,
    pub base: String,
    pub title: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub assignee: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub assignees: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub reviewers: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub team_reviewers: Vec<String>,
    #[serde(default)]
    pub milestone: i64,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub labels: Vec<i64>,
    #[serde(
        rename = "due_date",
        default,
        with = "nullable_rfc3339_option",
        skip_serializing_if = "Option::is_none"
    )]
    pub deadline: Option<time::OffsetDateTime>,
}

mod nullable_rfc3339_option {
    use serde::{Deserializer, Serializer};
    use time::OffsetDateTime;

    /// Serialize an optional RFC 3339 timestamp for serde.
    pub fn serialize<S>(opt: &Option<OffsetDateTime>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match opt {
            Some(dt) => {
                let formatted = dt
                    .format(&time::format_description::well_known::Rfc3339)
                    .map_err(serde::ser::Error::custom)?;
                serializer.serialize_str(&formatted)
            }
            None => serializer.serialize_none(),
        }
    }

    /// Deserialize an optional RFC 3339 timestamp for serde.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<OffsetDateTime>, D::Error>
    where
        D: Deserializer<'de>,
    {
        use serde::Deserialize;
        let opt: Option<String> = Option::deserialize(deserializer)?;
        match opt {
            None => Ok(None),
            Some(ref s) => {
                let dt = OffsetDateTime::parse(s, &time::format_description::well_known::Rfc3339)
                    .map_err(serde::de::Error::custom)?;
                Ok(Some(dt))
            }
        }
    }
}

/// EditPullRequestOption options when modify pull request
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
/// Options for Edit Pull Request Option.
pub struct EditPullRequestOption {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub base: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub assignee: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub assignees: Vec<String>,
    #[serde(default)]
    pub milestone: i64,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub labels: Vec<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub state: Option<StateType>,
    #[serde(
        rename = "due_date",
        default,
        with = "nullable_rfc3339_option",
        skip_serializing_if = "Option::is_none"
    )]
    pub deadline: Option<time::OffsetDateTime>,
    #[serde(rename = "unset_due_date", skip_serializing_if = "Option::is_none")]
    pub remove_deadline: Option<bool>,
    #[serde(
        rename = "allow_maintainer_edit",
        skip_serializing_if = "Option::is_none"
    )]
    pub allow_maintainer_edit: Option<bool>,
}

impl EditPullRequestOption {
    /// Validate the EditPullRequestOption struct
    pub fn validate(&self) -> crate::Result<()> {
        if let Some(ref title) = self.title
            && title.trim().is_empty()
        {
            return Err(crate::Error::Validation("title is empty".to_string()));
        }
        Ok(())
    }
}

/// MergePullRequestOption options when merging a pull request
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
/// Options for Merge Pull Request Option.
pub struct MergePullRequestOption {
    #[serde(rename = "Do", skip_serializing_if = "Option::is_none")]
    pub style: Option<MergeStyle>,
    #[serde(rename = "MergeCommitID", skip_serializing_if = "Option::is_none")]
    pub merge_commit_id: Option<String>,
    #[serde(rename = "MergeTitleField", skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(rename = "MergeMessageField", skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    #[serde(rename = "delete_branch_after_merge")]
    pub delete_branch_after_merge: bool,
    #[serde(rename = "force_merge")]
    pub force_merge: bool,
    #[serde(rename = "head_commit_id", skip_serializing_if = "Option::is_none")]
    pub head_commit_id: Option<String>,
    #[serde(rename = "merge_when_checks_succeed")]
    pub merge_when_checks_succeed: bool,
}

/// PullRequestDiffOptions options for GET `/repos/<owner>/<repo>/pulls/<idx>.[diff|patch]`
#[derive(Debug, Clone, Default)]
/// Options for Pull Request Diff Option.
pub struct PullRequestDiffOptions {
    /// Include binary file changes when requesting a .diff
    pub binary: bool,
}

impl QueryEncode for PullRequestDiffOptions {
    fn query_encode(&self) -> String {
        format!("binary={}", self.binary)
    }
}

/// ListPullRequestCommitsOptions options for listing pull request commits
#[derive(Debug, Clone, Default)]
/// Options for List Pull Request Commits Option.
pub struct ListPullRequestCommitsOptions {
    pub list_options: ListOptions,
}

impl QueryEncode for ListPullRequestCommitsOptions {
    fn query_encode(&self) -> String {
        self.list_options.query_encode()
    }
}

/// ListPullRequestFilesOptions options for listing pull request files
#[derive(Debug, Clone, Default)]
/// Options for List Pull Request Files Option.
pub struct ListPullRequestFilesOptions {
    pub list_options: ListOptions,
}

impl QueryEncode for ListPullRequestFilesOptions {
    fn query_encode(&self) -> String {
        self.list_options.query_encode()
    }
}

// ── pull_review.go ───────────────────────────────────────────────

/// ListPullReviewsOptions options for listing PullReviews
#[derive(Debug, Clone, Default)]
/// Options for List Pull Reviews Option.
pub struct ListPullReviewsOptions {
    pub list_options: ListOptions,
}

impl QueryEncode for ListPullReviewsOptions {
    fn query_encode(&self) -> String {
        self.list_options.query_encode()
    }
}

/// CreatePullReviewOptions are options to create a pull review
#[derive(Debug, Clone, Serialize, Deserialize)]
/// Options for Create Pull Review Option.
pub struct CreatePullReviewOptions {
    #[serde(rename = "event", skip_serializing_if = "Option::is_none")]
    pub state: Option<ReviewStateType>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
    #[serde(rename = "commit_id", skip_serializing_if = "Option::is_none")]
    pub commit_id: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub comments: Vec<CreatePullReviewComment>,
}

impl CreatePullReviewOptions {
    /// Validate the CreatePullReviewOptions struct
    pub fn validate(&self) -> crate::Result<()> {
        if self.state != Some(ReviewStateType::Approved)
            && self.comments.is_empty()
            && self.body.as_ref().is_some_and(|b| b.trim().is_empty())
        {
            return Err(crate::Error::Validation("body is empty".to_string()));
        }
        for comment in &self.comments {
            comment.validate()?;
        }
        Ok(())
    }
}

/// CreatePullReviewComment represent a review comment for creation api
#[derive(Debug, Clone, Serialize, Deserialize)]
/// Options for Create Pull Review Comment.
pub struct CreatePullReviewComment {
    /// the tree path
    pub path: String,
    pub body: String,
    /// if comment to old file line or 0
    #[serde(rename = "old_position")]
    pub old_line_num: i64,
    /// if comment to new file line or 0
    #[serde(rename = "new_position")]
    pub new_line_num: i64,
}

impl CreatePullReviewComment {
    /// Validate the CreatePullReviewComment struct
    pub fn validate(&self) -> crate::Result<()> {
        if self.body.trim().is_empty() {
            return Err(crate::Error::Validation("body is empty".to_string()));
        }
        if self.old_line_num != 0 && self.new_line_num != 0 {
            return Err(crate::Error::Validation(
                "old and new line num are set, cant identify the code comment position".to_string(),
            ));
        }
        Ok(())
    }
}

/// SubmitPullReviewOptions are options to submit a pending pull review
#[derive(Debug, Clone, Serialize, Deserialize)]
/// Options for Submit Pull Review Option.
pub struct SubmitPullReviewOptions {
    #[serde(rename = "event", skip_serializing_if = "Option::is_none")]
    pub state: Option<ReviewStateType>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
}

impl SubmitPullReviewOptions {
    /// Validate the SubmitPullReviewOptions struct
    pub fn validate(&self) -> crate::Result<()> {
        if self.state != Some(ReviewStateType::Approved)
            && self.body.as_ref().is_some_and(|b| b.trim().is_empty())
        {
            return Err(crate::Error::Validation("body is empty".to_string()));
        }
        Ok(())
    }
}

/// DismissPullReviewOptions are options to dismiss a pull review
#[derive(Debug, Clone, Serialize, Deserialize)]
/// Options for Dismiss Pull Review Option.
pub struct DismissPullReviewOptions {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

/// PullReviewRequestOptions are options to add or remove pull review requests
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
/// Options for Pull Review Request Option.
pub struct PullReviewRequestOptions {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub reviewers: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub team_reviewers: Vec<String>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_edit_pull_request_option_validate_success() {
        let opt = EditPullRequestOption {
            title: Some("new title".to_string()),
            ..Default::default()
        };
        assert!(opt.validate().is_ok());
    }

    #[test]
    fn test_edit_pull_request_option_validate_empty_title() {
        let opt = EditPullRequestOption {
            title: Some("   ".to_string()),
            ..Default::default()
        };
        assert!(opt.validate().is_err());
    }

    #[test]
    fn test_create_pull_review_options_validate_approved() {
        let opt = CreatePullReviewOptions {
            state: Some(ReviewStateType::Approved),
            body: None,
            commit_id: None,
            comments: Vec::new(),
        };
        assert!(opt.validate().is_ok());
    }

    #[test]
    fn test_create_pull_review_options_validate_empty_body() {
        let opt = CreatePullReviewOptions {
            state: None,
            body: Some("   ".to_string()),
            commit_id: None,
            comments: Vec::new(),
        };
        assert!(opt.validate().is_err());
    }

    #[test]
    fn test_create_pull_review_options_validate_with_comments() {
        let opt = CreatePullReviewOptions {
            state: None,
            body: Some("   ".to_string()),
            commit_id: None,
            comments: vec![CreatePullReviewComment {
                path: "main.rs".to_string(),
                body: "fix this".to_string(),
                old_line_num: 0,
                new_line_num: 10,
            }],
        };
        assert!(opt.validate().is_ok());
    }

    #[test]
    fn test_create_pull_review_comment_validate_success() {
        let comment = CreatePullReviewComment {
            path: "main.rs".to_string(),
            body: "fix this".to_string(),
            old_line_num: 0,
            new_line_num: 10,
        };
        assert!(comment.validate().is_ok());
    }

    #[test]
    fn test_create_pull_review_comment_validate_empty_body() {
        let comment = CreatePullReviewComment {
            path: "main.rs".to_string(),
            body: String::new(),
            old_line_num: 0,
            new_line_num: 10,
        };
        assert!(comment.validate().is_err());
    }

    #[test]
    fn test_create_pull_review_comment_validate_both_lines_set() {
        let comment = CreatePullReviewComment {
            path: "main.rs".to_string(),
            body: "fix this".to_string(),
            old_line_num: 5,
            new_line_num: 10,
        };
        assert!(comment.validate().is_err());
    }

    #[test]
    fn test_submit_pull_review_options_validate_approved() {
        let opt = SubmitPullReviewOptions {
            state: Some(ReviewStateType::Approved),
            body: None,
        };
        assert!(opt.validate().is_ok());
    }

    #[test]
    fn test_submit_pull_review_options_validate_empty_body() {
        let opt = SubmitPullReviewOptions {
            state: None,
            body: Some("   ".to_string()),
        };
        assert!(opt.validate().is_err());
    }
}