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
// 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 derive_builder::Builder;

use crate::api::common::{AccessLevel, SortOrder};
use crate::api::endpoint_prelude::*;
use crate::api::ParamValue;

/// Keys group results may be ordered by.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GroupOrderBy {
    /// Order by the name of the group.
    Name,
    /// Order by the full path of the group.
    Path,
    /// Order by the group ID.
    Id,
}

impl Default for GroupOrderBy {
    fn default() -> Self {
        GroupOrderBy::Name
    }
}

impl GroupOrderBy {
    /// The ordering as a query parameter.
    fn as_str(self) -> &'static str {
        match self {
            GroupOrderBy::Name => "name",
            GroupOrderBy::Path => "path",
            GroupOrderBy::Id => "id",
        }
    }
}

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

/// Query for groups on an instance.
#[derive(Debug, Builder)]
#[builder(setter(strip_option))]
pub struct Groups<'a> {
    /// Search for groups using a query string.
    ///
    /// The search query will be escaped automatically.
    #[builder(setter(into), default)]
    search: Option<Cow<'a, str>>,

    /// Skip groups with the given IDs.
    #[builder(setter(name = "_skip_groups"), default, private)]
    skip_groups: BTreeSet<u64>,
    /// Show all groups with access.
    ///
    /// Note that the default for this endpoint differs based on whether the API caller has
    /// administrator privileges or not.
    #[builder(default)]
    all_available: Option<bool>,
    /// Filter owned by those owned by the API caller.
    #[builder(default)]
    owned: Option<bool>,
    /// Filter groups by those where the API caller has a minimum access level.
    #[builder(default)]
    min_access_level: Option<AccessLevel>,

    /// Include project statistics in the results.
    #[builder(default)]
    statistics: Option<bool>,
    /// Include custom attributes in th response.
    #[builder(default)]
    with_custom_attributes: Option<bool>,

    /// Order results by a given key.
    #[builder(default)]
    order_by: Option<GroupOrderBy>,
    /// The sort order for return results.
    #[builder(default)]
    sort: Option<SortOrder>,
}

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

impl<'a> GroupsBuilder<'a> {
    /// Skip the given group ID.
    pub fn skip_group(&mut self, group: u64) -> &mut Self {
        self.skip_groups
            .get_or_insert_with(BTreeSet::new)
            .insert(group);
        self
    }

    /// Skip the given group IDs.
    pub fn skip_groups<I>(&mut self, iter: I) -> &mut Self
    where
        I: Iterator<Item = u64>,
    {
        self.skip_groups
            .get_or_insert_with(BTreeSet::new)
            .extend(iter);
        self
    }
}

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

    fn endpoint(&self) -> Cow<'static, str> {
        "groups".into()
    }

    fn parameters(&self) -> QueryParams {
        let mut params = QueryParams::default();

        params
            .push_opt("search", self.search.as_ref())
            .extend(
                self.skip_groups
                    .iter()
                    .map(|&value| ("skip_groups[]", value)),
            )
            .push_opt("all_available", self.all_available)
            .push_opt("owned", self.owned)
            .push_opt(
                "min_access_level",
                self.min_access_level.map(|level| level.as_u64()),
            )
            .push_opt("statistics", self.statistics)
            .push_opt("with_custom_attributes", self.with_custom_attributes)
            .push_opt("order_by", self.order_by)
            .push_opt("sort", self.sort);

        params
    }
}

impl<'a> Pageable for Groups<'a> {}

#[cfg(test)]
mod tests {
    use crate::api::common::{AccessLevel, SortOrder};
    use crate::api::groups::{GroupOrderBy, Groups};
    use crate::api::{self, Query};
    use crate::test::client::{ExpectedUrl, SingleTestClient};

    #[test]
    fn order_by_default() {
        assert_eq!(GroupOrderBy::default(), GroupOrderBy::Name);
    }

    #[test]
    fn order_by_as_str() {
        let items = &[
            (GroupOrderBy::Name, "name"),
            (GroupOrderBy::Path, "path"),
            (GroupOrderBy::Id, "id"),
        ];

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

    #[test]
    fn defaults_are_sufficient() {
        Groups::builder().build().unwrap();
    }

    #[test]
    fn endpoint() {
        let endpoint = ExpectedUrl::builder().endpoint("groups").build().unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = Groups::builder().build().unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_search() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("groups")
            .add_query_params(&[("search", "query")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = Groups::builder().search("query").build().unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_skip_groups() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("groups")
            .add_query_params(&[("skip_groups[]", "1"), ("skip_groups[]", "2")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = Groups::builder()
            .skip_group(1)
            .skip_groups([1, 2].iter().copied())
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_all_available() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("groups")
            .add_query_params(&[("all_available", "true")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = Groups::builder().all_available(true).build().unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_owned() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("groups")
            .add_query_params(&[("owned", "false")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = Groups::builder().owned(false).build().unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_min_access_level() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("groups")
            .add_query_params(&[("min_access_level", "30")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = Groups::builder()
            .min_access_level(AccessLevel::Developer)
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_statistics() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("groups")
            .add_query_params(&[("statistics", "false")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = Groups::builder().statistics(false).build().unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_with_custom_attributes() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("groups")
            .add_query_params(&[("with_custom_attributes", "true")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = Groups::builder()
            .with_custom_attributes(true)
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_order_by() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("groups")
            .add_query_params(&[("order_by", "path")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = Groups::builder()
            .order_by(GroupOrderBy::Path)
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_sort() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("groups")
            .add_query_params(&[("sort", "asc")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = Groups::builder()
            .sort(SortOrder::Ascending)
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }
}