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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::collections::BTreeSet;

use chrono::{DateTime, NaiveDate, Utc};
use derive_builder::Builder;
use itertools::Itertools;

use crate::api::common::NameOrId;
use crate::api::endpoint_prelude::*;
use crate::api::ParamValue;

/// States an issue may be set to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IssueStateEvent {
    /// Close the issue.
    Close,
    /// Reopen a closed issue.
    Reopen,
}

impl IssueStateEvent {
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            IssueStateEvent::Close => "close",
            IssueStateEvent::Reopen => "reopen",
        }
    }
}

impl ParamValue<'static> for IssueStateEvent {
    fn as_value(self) -> Cow<'static, str> {
        self.as_str().into()
    }
}

#[derive(Debug, Clone)]
enum IssueAssignees {
    Unassigned,
    Assignees(BTreeSet<u64>),
}

#[derive(Debug, Clone)]
enum IssueLabels<'a> {
    Unlabeled,
    Labeled(BTreeSet<Cow<'a, str>>),
}

impl<'a, 'b: 'a> ParamValue<'a> for &'b IssueLabels<'a> {
    fn as_value(self) -> Cow<'a, str> {
        match self {
            IssueLabels::Unlabeled => "".into(),
            IssueLabels::Labeled(labels) => format!("{}", labels.iter().format(",")).into(),
        }
    }
}

/// Create a new issue on a project.
#[derive(Debug, Builder)]
#[builder(setter(strip_option))]
pub struct EditIssue<'a> {
    /// The project to add the issue to.
    #[builder(setter(into))]
    project: NameOrId<'a>,
    /// The internal IID of the issue.
    issue: u64,

    /// The title of the new issue.
    #[builder(setter(into), default)]
    title: Option<Cow<'a, str>>,
    /// The description of the issue.
    #[builder(setter(into), default)]
    description: Option<Cow<'a, str>>,

    /// Assignees for the issue.
    #[builder(setter(name = "_assignee_ids"), default, private)]
    assignee_ids: Option<IssueAssignees>,
    /// The ID of a milestone to add the issue to.
    #[builder(default)]
    milestone_id: Option<u64>,
    /// Labels to set on the issue.
    #[builder(setter(name = "_labels"), default, private)]
    labels: Option<IssueLabels<'a>>,
    /// Change the state of the issue.
    #[builder(default)]
    state_event: Option<IssueStateEvent>,
    /// Set the last-updated time for the issue.
    #[builder(default)]
    updated_at: Option<DateTime<Utc>>,
    /// Set the due date for the issue.
    #[builder(default)]
    due_date: Option<NaiveDate>,
    /// Set the weight of the issue.
    #[builder(default)]
    weight: Option<u64>,
    /// Set whether discussion of the issue should be locked or not.
    #[builder(default)]
    discussion_locked: Option<bool>,
    /// The ID of the epic to add the issue to.
    #[builder(default)]
    epic_id: Option<u64>,

    /// The internal ID of the epic to add the issue to.
    #[deprecated(note = "use `epic_id` instead")]
    #[builder(default)]
    epic_iid: Option<u64>,
}

impl<'a> EditIssue<'a> {
    /// Create a builder for the endpoint.
    pub fn builder() -> EditIssueBuilder<'a> {
        EditIssueBuilder::default()
    }
}

impl<'a> EditIssueBuilder<'a> {
    /// Set the issue ID.
    #[deprecated(note = "use `issue` instead")]
    pub fn issue_iid(&mut self, issue_iid: u64) -> &mut Self {
        self.issue = Some(issue_iid);
        self
    }

    /// Unassign the issue.
    pub fn unassign(&mut self) -> &mut Self {
        self.assignee_ids = Some(Some(IssueAssignees::Unassigned));
        self
    }

    /// Assign the issue to a user.
    pub fn assignee_id(&mut self, assignee: u64) -> &mut Self {
        let assignees =
            if let Some(Some(IssueAssignees::Assignees(mut set))) = self.assignee_ids.take() {
                set.insert(assignee);
                set
            } else {
                let mut set = BTreeSet::new();
                set.insert(assignee);
                set
            };
        self.assignee_ids = Some(Some(IssueAssignees::Assignees(assignees)));
        self
    }

    /// Assigne the issue to a set of users.
    pub fn assignee_ids<I>(&mut self, iter: I) -> &mut Self
    where
        I: Iterator<Item = u64>,
    {
        let assignees =
            if let Some(Some(IssueAssignees::Assignees(mut set))) = self.assignee_ids.take() {
                set.extend(iter);
                set
            } else {
                iter.collect()
            };
        self.assignee_ids = Some(Some(IssueAssignees::Assignees(assignees)));
        self
    }

    /// Remove all labels from the issue.
    pub fn remove_labels(&mut self) -> &mut Self {
        self.labels = Some(Some(IssueLabels::Unlabeled));
        self
    }

    /// Add a label to the issue.
    ///
    /// Note that the list of labels sent will replace the set on the instance. This only adds it
    /// to the list of labels to add to the set before sending it to the instance.
    pub fn label<L>(&mut self, label: L) -> &mut Self
    where
        L: Into<Cow<'a, str>>,
    {
        let label = label.into();
        let labels = if let Some(Some(IssueLabels::Labeled(mut set))) = self.labels.take() {
            set.insert(label);
            set
        } else {
            let mut set = BTreeSet::new();
            set.insert(label);
            set
        };
        self.labels = Some(Some(IssueLabels::Labeled(labels)));
        self
    }

    /// Add a set of labels to the issue.
    ///
    /// Note that the list of labels sent will replace the set on the instance. This only adds it
    /// to the list of labels to add to the set before sending it to the instance.
    pub fn labels<I, L>(&mut self, iter: I) -> &mut Self
    where
        I: IntoIterator<Item = L>,
        L: Into<Cow<'a, str>>,
    {
        let iter = iter.into_iter().map(Into::into);
        let labels = if let Some(Some(IssueLabels::Labeled(mut set))) = self.labels.take() {
            set.extend(iter);
            set
        } else {
            iter.collect()
        };
        self.labels = Some(Some(IssueLabels::Labeled(labels)));
        self
    }
}

impl<'a> Endpoint for EditIssue<'a> {
    fn method(&self) -> Method {
        Method::PUT
    }

    fn endpoint(&self) -> Cow<'static, str> {
        format!("projects/{}/issues/{}", self.project, self.issue).into()
    }

    fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, BodyError> {
        let mut params = FormParams::default();

        params
            .push_opt("title", self.title.as_ref())
            .push_opt("description", self.description.as_ref())
            .push_opt("milestone_id", self.milestone_id)
            .push_opt("labels", self.labels.as_ref())
            .push_opt("state_event", self.state_event)
            .push_opt("updated_at", self.updated_at)
            .push_opt("due_date", self.due_date)
            .push_opt("weight", self.weight)
            .push_opt("discussion_locked", self.discussion_locked)
            .push_opt("epic_id", self.epic_id);

        if let Some(assignees) = self.assignee_ids.as_ref() {
            match assignees {
                IssueAssignees::Unassigned => {
                    params.push("assignee_ids[]", "0");
                },
                IssueAssignees::Assignees(ids) => {
                    params.extend(ids.iter().map(|&value| ("assignee_ids[]", value)));
                },
            }
        }

        #[allow(deprecated)]
        {
            params.push_opt("epic_iid", self.epic_iid);
        }

        params.into_body()
    }
}

#[cfg(test)]
mod tests {
    use chrono::{NaiveDate, TimeZone, Utc};
    use http::Method;

    use crate::api::projects::issues::{EditIssue, IssueStateEvent};
    use crate::api::{self, Query};
    use crate::test::client::{ExpectedUrl, SingleTestClient};

    #[test]
    fn issue_state_event_as_str() {
        let items = &[
            (IssueStateEvent::Close, "close"),
            (IssueStateEvent::Reopen, "reopen"),
        ];

        for (i, s) in items {
            assert_eq!(i.as_str(), *s);
        }
    }

    #[test]
    fn project_and_issue_are_necessary() {
        let err = EditIssue::builder().build().unwrap_err();
        assert_eq!(err, "`project` must be initialized");
    }

    #[test]
    fn project_is_necessary() {
        let err = EditIssue::builder().issue(1).build().unwrap_err();
        assert_eq!(err, "`project` must be initialized");
    }

    #[test]
    fn issue_is_necessary() {
        let err = EditIssue::builder().project(1).build().unwrap_err();
        assert_eq!(err, "`issue` must be initialized");
    }

    #[test]
    fn project_and_issue_are_sufficient() {
        EditIssue::builder().project(1).issue(1).build().unwrap();
    }

    #[test]
    #[allow(deprecated)]
    fn project_and_issue_iid_are_sufficient() {
        EditIssue::builder()
            .project(1)
            .issue_iid(1)
            .build()
            .unwrap();
    }

    #[test]
    fn endpoint() {
        let endpoint = ExpectedUrl::builder()
            .method(Method::PUT)
            .endpoint("projects/simple%2Fproject/issues/1")
            .content_type("application/x-www-form-urlencoded")
            .body_str("")
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = EditIssue::builder()
            .project("simple/project")
            .issue(1)
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_title() {
        let endpoint = ExpectedUrl::builder()
            .method(Method::PUT)
            .endpoint("projects/simple%2Fproject/issues/1")
            .content_type("application/x-www-form-urlencoded")
            .body_str("title=title")
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = EditIssue::builder()
            .project("simple/project")
            .issue(1)
            .title("title")
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_description() {
        let endpoint = ExpectedUrl::builder()
            .method(Method::PUT)
            .endpoint("projects/simple%2Fproject/issues/1")
            .content_type("application/x-www-form-urlencoded")
            .body_str("description=description")
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = EditIssue::builder()
            .project("simple/project")
            .issue(1)
            .description("description")
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_assignee_ids() {
        let endpoint = ExpectedUrl::builder()
            .method(Method::PUT)
            .endpoint("projects/simple%2Fproject/issues/1")
            .content_type("application/x-www-form-urlencoded")
            .body_str(concat!("assignee_ids%5B%5D=1", "&assignee_ids%5B%5D=2"))
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = EditIssue::builder()
            .project("simple/project")
            .issue(1)
            .assignee_id(1)
            .assignee_ids([1, 2].iter().copied())
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_assignee_ids_unassign() {
        let endpoint = ExpectedUrl::builder()
            .method(Method::PUT)
            .endpoint("projects/simple%2Fproject/issues/1")
            .content_type("application/x-www-form-urlencoded")
            .body_str("assignee_ids%5B%5D=0")
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = EditIssue::builder()
            .project("simple/project")
            .issue(1)
            .unassign()
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_milestone_id() {
        let endpoint = ExpectedUrl::builder()
            .method(Method::PUT)
            .endpoint("projects/simple%2Fproject/issues/1")
            .content_type("application/x-www-form-urlencoded")
            .body_str("milestone_id=1")
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = EditIssue::builder()
            .project("simple/project")
            .issue(1)
            .milestone_id(1)
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_labels() {
        let endpoint = ExpectedUrl::builder()
            .method(Method::PUT)
            .endpoint("projects/simple%2Fproject/issues/1")
            .content_type("application/x-www-form-urlencoded")
            .body_str("labels=label")
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = EditIssue::builder()
            .project("simple/project")
            .issue(1)
            .label("label")
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_labels_multiple() {
        let endpoint = ExpectedUrl::builder()
            .method(Method::PUT)
            .endpoint("projects/simple%2Fproject/issues/1")
            .content_type("application/x-www-form-urlencoded")
            .body_str("labels=label1%2Clabel2")
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = EditIssue::builder()
            .project("simple/project")
            .issue(1)
            .labels(["label1", "label2"].iter().copied())
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_labels_remove() {
        let endpoint = ExpectedUrl::builder()
            .method(Method::PUT)
            .endpoint("projects/simple%2Fproject/issues/1")
            .content_type("application/x-www-form-urlencoded")
            .body_str("labels=")
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = EditIssue::builder()
            .project("simple/project")
            .issue(1)
            .remove_labels()
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_state_event() {
        let endpoint = ExpectedUrl::builder()
            .method(Method::PUT)
            .endpoint("projects/simple%2Fproject/issues/1")
            .content_type("application/x-www-form-urlencoded")
            .body_str("state_event=close")
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = EditIssue::builder()
            .project("simple/project")
            .issue(1)
            .state_event(IssueStateEvent::Close)
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_updated_at() {
        let endpoint = ExpectedUrl::builder()
            .method(Method::PUT)
            .endpoint("projects/simple%2Fproject/issues/1")
            .content_type("application/x-www-form-urlencoded")
            .body_str("updated_at=2020-01-01T00%3A00%3A00Z")
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = EditIssue::builder()
            .project("simple/project")
            .issue(1)
            .updated_at(Utc.ymd(2020, 1, 1).and_hms_milli(0, 0, 0, 0))
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_due_date() {
        let endpoint = ExpectedUrl::builder()
            .method(Method::PUT)
            .endpoint("projects/simple%2Fproject/issues/1")
            .content_type("application/x-www-form-urlencoded")
            .body_str("due_date=2020-01-01")
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = EditIssue::builder()
            .project("simple/project")
            .issue(1)
            .due_date(NaiveDate::from_ymd(2020, 1, 1))
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_weight() {
        let endpoint = ExpectedUrl::builder()
            .method(Method::PUT)
            .endpoint("projects/simple%2Fproject/issues/1")
            .content_type("application/x-www-form-urlencoded")
            .body_str("weight=1")
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = EditIssue::builder()
            .project("simple/project")
            .issue(1)
            .weight(1)
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_discussion_locked() {
        let endpoint = ExpectedUrl::builder()
            .method(Method::PUT)
            .endpoint("projects/simple%2Fproject/issues/1")
            .content_type("application/x-www-form-urlencoded")
            .body_str("discussion_locked=true")
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = EditIssue::builder()
            .project("simple/project")
            .issue(1)
            .discussion_locked(true)
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_epic_id() {
        let endpoint = ExpectedUrl::builder()
            .method(Method::PUT)
            .endpoint("projects/simple%2Fproject/issues/1")
            .content_type("application/x-www-form-urlencoded")
            .body_str("epic_id=1")
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = EditIssue::builder()
            .project("simple/project")
            .issue(1)
            .epic_id(1)
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    #[allow(deprecated)]
    fn endpoint_epic_iid() {
        let endpoint = ExpectedUrl::builder()
            .method(Method::PUT)
            .endpoint("projects/simple%2Fproject/issues/1")
            .content_type("application/x-www-form-urlencoded")
            .body_str("epic_iid=1")
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = EditIssue::builder()
            .project("simple/project")
            .issue(1)
            .epic_iid(1)
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }
}