bugbite 0.0.14

library for bug, issue, and ticket mangling
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
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
use std::fmt;

use indexmap::IndexMap;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;

use crate::objects::bugzilla::{Bug, Flag};
use crate::service::bugzilla::Bugzilla;
use crate::traits::{InjectAuth, Merge, MergeOption, RequestSend, RequestTemplate, WebService};
use crate::Error;

#[derive(Serialize, Debug, Clone, PartialEq)]
pub struct Request {
    #[serde(skip)]
    service: Bugzilla,
    #[serde(flatten)]
    pub params: Parameters,
}

impl RequestSend for Request {
    type Output = u64;

    async fn send(&self) -> crate::Result<Self::Output> {
        let url = self.service.config().base.join("rest/bug")?;
        let params = self.encode()?;
        let request = self
            .service
            .client()
            .post(url)
            .json(&params)
            .auth(&self.service)?;
        let response = request.send().await?;
        let mut data = self.service.parse_response(response).await?;
        serde_json::from_value(data["id"].take())
            .map_err(|e| Error::InvalidResponse(format!("failed deserializing id: {e}")))
    }
}

impl RequestTemplate for Request {
    type Params = Parameters;
    type Service = Bugzilla;
    const TYPE: &'static str = "create";

    fn service(&self) -> &Self::Service {
        &self.service
    }

    fn params(&mut self) -> &mut Self::Params {
        &mut self.params
    }
}

impl Request {
    pub(super) fn new(service: &Bugzilla) -> Self {
        Self {
            service: service.clone(),
            params: Default::default(),
        }
    }

    /// Encode parameters into the form required for the request.
    fn encode(&self) -> crate::Result<RequestParameters> {
        let params = RequestParameters {
            // required fields with defaults
            op_sys: self.params.os.as_deref().unwrap_or("All"),
            platform: self.params.platform.as_deref().unwrap_or("All"),
            priority: self.params.priority.as_deref().unwrap_or("Normal"),
            severity: self.params.severity.as_deref().unwrap_or("normal"),
            version: self.params.version.as_deref().unwrap_or("unspecified"),

            // required fields without defaults
            component: self.params.component.as_deref().unwrap_or_default(),
            description: self.params.description.as_deref().unwrap_or_default(),
            product: self.params.product.as_deref().unwrap_or_default(),
            summary: self.params.summary.as_deref().unwrap_or_default(),

            // optional fields
            alias: self.params.alias.as_deref(),
            assigned_to: self
                .params
                .assignee
                .as_deref()
                .map(|x| self.service.replace_user_alias(x)),
            blocks: self.params.blocks.as_deref(),
            cc: self.params.cc.as_deref(),
            depends_on: self.params.depends.as_deref(),
            flags: self.params.flags.as_deref(),
            groups: self.params.groups.as_deref(),
            keywords: self.params.keywords.as_deref(),
            qa_contact: self
                .params
                .qa
                .as_deref()
                .map(|x| self.service.replace_user_alias(x)),
            resolution: self.params.resolution.as_deref(),
            see_also: self.params.see_also.as_deref(),
            status: self.params.status.as_deref(),
            target_milestone: self.params.target.as_deref(),
            url: self.params.url.as_deref(),
            whiteboard: self.params.whiteboard.as_deref(),
            custom_fields: self.params.custom_fields.as_ref(),
        };

        // verify required fields are non-empty
        let mut missing = vec![];
        for (value, name) in [
            (params.component, "component"),
            (params.description, "description"),
            (params.op_sys, "os"),
            (params.platform, "platform"),
            (params.priority, "priority"),
            (params.product, "product"),
            (params.severity, "severity"),
            (params.summary, "summary"),
            (params.version, "version"),
        ] {
            if value.is_empty() {
                missing.push(name);
            }
        }

        if !missing.is_empty() {
            let fields = missing.iter().sorted().join(", ");
            return Err(Error::InvalidRequest(format!(
                "missing required fields: {fields}"
            )));
        }

        Ok(params)
    }

    pub fn alias<I, S>(&mut self, value: I) -> &mut Self
    where
        I: IntoIterator<Item = S>,
        S: fmt::Display,
    {
        self.params.alias = Some(value.into_iter().map(|x| x.to_string()).collect());
        self
    }

    pub fn assignee<S>(&mut self, value: S) -> &mut Self
    where
        S: fmt::Display,
    {
        self.params.assignee = Some(value.to_string());
        self
    }

    pub fn blocks<I, S>(&mut self, value: I) -> &mut Self
    where
        I: IntoIterator<Item = S>,
        S: fmt::Display,
    {
        self.params.blocks = Some(value.into_iter().map(|x| x.to_string()).collect());
        self
    }

    pub fn cc<I, S>(&mut self, value: I) -> &mut Self
    where
        I: IntoIterator<Item = S>,
        S: fmt::Display,
    {
        self.params.cc = Some(value.into_iter().map(|x| x.to_string()).collect());
        self
    }

    pub fn component<S>(&mut self, value: S) -> &mut Self
    where
        S: fmt::Display,
    {
        self.params.component = Some(value.to_string());
        self
    }

    pub fn depends<I, S>(&mut self, value: I) -> &mut Self
    where
        I: IntoIterator<Item = S>,
        S: fmt::Display,
    {
        self.params.depends = Some(value.into_iter().map(|x| x.to_string()).collect());
        self
    }

    pub fn description<S>(&mut self, value: S) -> &mut Self
    where
        S: fmt::Display,
    {
        self.params.description = Some(value.to_string());
        self
    }

    pub fn flags<I>(&mut self, value: I) -> &mut Self
    where
        I: IntoIterator<Item = Flag>,
    {
        self.params.flags = Some(value.into_iter().collect());
        self
    }

    pub fn groups<I, S>(&mut self, value: I) -> &mut Self
    where
        I: IntoIterator<Item = S>,
        S: fmt::Display,
    {
        self.params.groups = Some(value.into_iter().map(|x| x.to_string()).collect());
        self
    }

    pub fn keywords<I, S>(&mut self, value: I) -> &mut Self
    where
        I: IntoIterator<Item = S>,
        S: fmt::Display,
    {
        self.params.keywords = Some(value.into_iter().map(|x| x.to_string()).collect());
        self
    }

    pub fn os<S>(&mut self, value: S) -> &mut Self
    where
        S: fmt::Display,
    {
        self.params.os = Some(value.to_string());
        self
    }

    pub fn platform<S>(&mut self, value: S) -> &mut Self
    where
        S: fmt::Display,
    {
        self.params.platform = Some(value.to_string());
        self
    }

    pub fn priority<S>(&mut self, value: S) -> &mut Self
    where
        S: fmt::Display,
    {
        self.params.priority = Some(value.to_string());
        self
    }

    pub fn product<S>(&mut self, value: S) -> &mut Self
    where
        S: fmt::Display,
    {
        self.params.product = Some(value.to_string());
        self
    }

    pub fn qa<S>(&mut self, value: S) -> &mut Self
    where
        S: fmt::Display,
    {
        self.params.qa = Some(value.to_string());
        self
    }

    pub fn resolution<S>(&mut self, value: S) -> &mut Self
    where
        S: fmt::Display,
    {
        self.params.resolution = Some(value.to_string());
        self
    }

    pub fn see_also<I, S>(&mut self, value: I) -> &mut Self
    where
        I: IntoIterator<Item = S>,
        S: fmt::Display,
    {
        self.params.see_also = Some(value.into_iter().map(|x| x.to_string()).collect());
        self
    }

    pub fn severity<S>(&mut self, value: S) -> &mut Self
    where
        S: fmt::Display,
    {
        self.params.severity = Some(value.to_string());
        self
    }

    pub fn status<S>(&mut self, value: S) -> &mut Self
    where
        S: fmt::Display,
    {
        self.params.status = Some(value.to_string());
        self
    }

    pub fn summary<S>(&mut self, value: S) -> &mut Self
    where
        S: fmt::Display,
    {
        self.params.summary = Some(value.to_string());
        self
    }

    pub fn target<S>(&mut self, value: S) -> &mut Self
    where
        S: fmt::Display,
    {
        self.params.target = Some(value.to_string());
        self
    }

    pub fn url<S>(&mut self, value: S) -> &mut Self
    where
        S: fmt::Display,
    {
        self.params.url = Some(value.to_string());
        self
    }

    pub fn version<S>(&mut self, value: S) -> &mut Self
    where
        S: fmt::Display,
    {
        self.params.version = Some(value.to_string());
        self
    }

    pub fn whiteboard<S>(&mut self, value: S) -> &mut Self
    where
        S: fmt::Display,
    {
        self.params.whiteboard = Some(value.to_string());
        self
    }

    pub fn custom_fields<I, S1, S2>(&mut self, value: I) -> &mut Self
    where
        I: IntoIterator<Item = (S1, S2)>,
        S1: fmt::Display,
        S2: fmt::Display,
    {
        self.params.custom_fields = Some(
            value
                .into_iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect(),
        );
        self
    }
}

/// Bug creation parameters.
#[skip_serializing_none]
#[derive(Deserialize, Serialize, Debug, Default, Clone, PartialEq, Eq)]
pub struct Parameters {
    pub alias: Option<Vec<String>>,
    pub assignee: Option<String>,
    pub blocks: Option<Vec<String>>,
    pub cc: Option<Vec<String>>,
    pub component: Option<String>,
    pub depends: Option<Vec<String>>,
    pub description: Option<String>,
    pub flags: Option<Vec<Flag>>,
    pub groups: Option<Vec<String>>,
    pub keywords: Option<Vec<String>>,
    pub os: Option<String>,
    pub platform: Option<String>,
    pub priority: Option<String>,
    pub product: Option<String>,
    pub qa: Option<String>,
    pub resolution: Option<String>,
    pub see_also: Option<Vec<String>>,
    pub severity: Option<String>,
    pub status: Option<String>,
    pub summary: Option<String>,
    pub target: Option<String>,
    pub url: Option<String>,
    pub version: Option<String>,
    pub whiteboard: Option<String>,

    #[serde(flatten)]
    pub custom_fields: Option<IndexMap<String, String>>,
}

impl Merge for Parameters {
    fn merge(&mut self, other: Self) {
        *self = Self {
            alias: self.alias.merge(other.alias),
            assignee: self.assignee.merge(other.assignee),
            blocks: self.blocks.merge(other.blocks),
            cc: self.cc.merge(other.cc),
            component: self.component.merge(other.component),
            custom_fields: self.custom_fields.merge(other.custom_fields),
            depends: self.depends.merge(other.depends),
            description: self.description.merge(other.description),
            flags: self.flags.merge(other.flags),
            groups: self.groups.merge(other.groups),
            keywords: self.keywords.merge(other.keywords),
            os: self.os.merge(other.os),
            platform: self.platform.merge(other.platform),
            priority: self.priority.merge(other.priority),
            product: self.product.merge(other.product),
            qa: self.qa.merge(other.qa),
            resolution: self.resolution.merge(other.resolution),
            see_also: self.see_also.merge(other.see_also),
            status: self.status.merge(other.status),
            severity: self.severity.merge(other.severity),
            target: self.target.merge(other.target),
            summary: self.summary.merge(other.summary),
            url: self.url.merge(other.url),
            version: self.version.merge(other.version),
            whiteboard: self.whiteboard.merge(other.whiteboard),
        }
    }
}

impl From<Bug> for Parameters {
    fn from(value: Bug) -> Self {
        Self {
            component: value.component,
            os: value.op_sys,
            platform: value.platform,
            priority: value.priority,
            product: value.product,
            severity: value.severity,
            version: value.version,
            ..Default::default()
        }
    }
}

/// Internal bug creation request parameters.
///
/// See https://bugzilla.readthedocs.io/en/latest/api/core/v1/bug.html#update-bug for more
/// information.
#[skip_serializing_none]
#[derive(Serialize)]
struct RequestParameters<'a> {
    // required fields
    component: &'a str,
    description: &'a str,
    op_sys: &'a str,
    platform: &'a str,
    priority: &'a str,
    product: &'a str,
    severity: &'a str,
    summary: &'a str,
    version: &'a str,

    // optional fields
    alias: Option<&'a [String]>,
    assigned_to: Option<&'a str>,
    blocks: Option<&'a [String]>,
    cc: Option<&'a [String]>,
    depends_on: Option<&'a [String]>,
    flags: Option<&'a [Flag]>,
    groups: Option<&'a [String]>,
    keywords: Option<&'a [String]>,
    qa_contact: Option<&'a str>,
    resolution: Option<&'a str>,
    see_also: Option<&'a [String]>,
    status: Option<&'a str>,
    target_milestone: Option<&'a str>,
    url: Option<&'a str>,
    whiteboard: Option<&'a str>,

    #[serde(flatten)]
    custom_fields: Option<&'a IndexMap<String, String>>,
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use crate::test::*;

    use super::*;

    #[tokio::test]
    async fn request() {
        let path = TESTDATA_PATH.join("bugzilla");
        let server = TestServer::new().await;
        let service = Bugzilla::builder(server.uri())
            .unwrap()
            .user("user")
            .password("pass")
            .build()
            .unwrap();

        // missing required fields without defaults
        let err = service.create().send().await.unwrap_err();
        assert!(matches!(err, Error::InvalidRequest(_)));
        assert_err_re!(
            err,
            "missing required fields: component, description, product, summary"
        );

        // empty required fields
        let err = service
            .create()
            .os("")
            .description("a")
            .summary("b")
            .send()
            .await
            .unwrap_err();
        assert!(matches!(err, Error::InvalidRequest(_)));
        assert_err_re!(err, "missing required fields: component, os, product");

        // create new request with default fields set
        let request = || {
            let mut req = service.create();
            req.component("TestComponent");
            req.product("TestProduct");
            req.description("description");
            req.summary("summary");
            req
        };

        server.respond(200, path.join("create/creation.json")).await;

        // valid
        let id = request().send().await.unwrap();
        assert_eq!(id, 123);

        // alias
        request().alias(["alias1", "alias2"]).send().await.unwrap();

        // assignee
        request().assignee("user").send().await.unwrap();

        // blocks
        request().blocks([1]).send().await.unwrap();
        request().blocks(["alias1", "alias2"]).send().await.unwrap();

        // cc
        request().cc(["user@email.com"]).send().await.unwrap();
        request()
            .cc(["user1@email.com", "user2@email.com"])
            .send()
            .await
            .unwrap();

        // component
        request().component("component").send().await.unwrap();

        // depends
        request().depends([1]).send().await.unwrap();
        request()
            .depends(["alias1", "alias2"])
            .send()
            .await
            .unwrap();

        // description
        request().description("description").send().await.unwrap();

        // flags
        let flag1 = Flag::from_str("flag1+").unwrap();
        let flag2 = Flag::from_str("flag2-").unwrap();
        let flag3 = Flag::from_str("flag3?").unwrap();
        request().flags([flag1, flag2, flag3]).send().await.unwrap();

        // groups
        request().groups(["group1", "group2"]).send().await.unwrap();

        // keywords
        request().keywords(["kw1", "kw2"]).send().await.unwrap();

        // os
        request().os("os").send().await.unwrap();

        // platform
        request().platform("platform").send().await.unwrap();

        // priority
        request().priority("normal").send().await.unwrap();

        // product
        request().product("product").send().await.unwrap();

        // qa
        request().qa("user@email.com").send().await.unwrap();

        // resolution
        request().resolution("fixed").send().await.unwrap();

        // see also
        request().see_also([36]).send().await.unwrap();
        request().see_also(["36"]).send().await.unwrap();
        request()
            .see_also(["https://link/to/external/bug"])
            .send()
            .await
            .unwrap();

        // severity
        request().severity("normal").send().await.unwrap();

        // status
        request().status("closed").send().await.unwrap();

        // summary
        request().summary("summary").send().await.unwrap();

        // target
        request().target("milestone").send().await.unwrap();

        // url
        request().url("https://link/to/site").send().await.unwrap();

        // version
        request().version("1.2.3").send().await.unwrap();

        // whiteboard
        request().whiteboard("note").send().await.unwrap();

        // custom fields
        request()
            .custom_fields([("name", "value")])
            .send()
            .await
            .unwrap();
    }
}