summaryrefslogtreecommitdiffstats
path: root/src/package/dependency/condition.rs
blob: c9b934ac17a0dbf0b7fccad9885fe3ccff6f2e54 (plain)
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
//
// Copyright (c) 2020-2021 science+computing ag and other contributors
//
// This program and the accompanying materials are made
// available under the terms of the Eclipse Public License 2.0
// which is available at https://www.eclipse.org/legal/epl-2.0/
//
// SPDX-License-Identifier: EPL-2.0
//

use std::collections::HashMap;

use serde::Deserialize;
use serde::Serialize;
use getset::Getters;
use anyhow::Result;

use crate::util::EnvironmentVariableName;
use crate::util::docker::ImageName;

/// The Condition type
///
/// This type represents a condition whether a dependency should be included in the package tree or
/// not.
///
/// Right now, we are supporting condition by environment (set or equal) or whether a specific
/// build image is used.
/// All these settings are optional, of course.
///
#[derive(Serialize, Deserialize, Getters, Clone, Debug, Eq, PartialEq)]
pub struct Condition {
    #[serde(rename = "has_env", skip_serializing_if = "Option::is_none")]
    #[getset(get = "pub")]
    pub(super) has_env: Option<OneOrMore<EnvironmentVariableName>>,

    #[serde(rename = "env_eq", skip_serializing_if = "Option::is_none")]
    #[getset(get = "pub")]
    pub(super) env_eq: Option<HashMap<EnvironmentVariableName, String>>,

    #[serde(rename = "in_image", skip_serializing_if = "Option::is_none")]
    #[getset(get = "pub")]
    pub(super) in_image: Option<OneOrMore<String>>,
}

impl Condition {
    #[cfg(test)]
    pub fn new(has_env: Option<OneOrMore<EnvironmentVariableName>>,
               env_eq: Option<HashMap<EnvironmentVariableName, String>>,
               in_image: Option<OneOrMore<String>>)
        -> Self
    {
        Condition { has_env, env_eq, in_image }
    }

    /// Check whether the condition matches a certain set of data
    ///
    /// # Return value
    ///
    /// Always returns Ok(_) in the current implementation
    pub fn matches(&self, data: &ConditionData<'_>) -> Result<bool> {
        if !self.matches_env_cond(data)? {
            return Ok(false)
        }

        if !self.matches_env_eq_cond(data)? {
            return Ok(false)
        }

        if !self.matches_in_image_cond(data)? {
            return Ok(false)
        }

        Ok(true)
    }

    fn matches_env_cond(&self, data: &ConditionData<'_>) -> Result<bool> {
        if let Some(has_env_cond) = self.has_env.as_ref() {
            let b = match has_env_cond {
                OneOrMore::One(env) => data.env.iter().any(|(name, _)| env == name),
                OneOrMore::More(envs) => envs.iter().all(|required_env| {
                    data.env
                        .iter()
                        .any(|(name, _)| name == required_env)
                })
            };

            if !b {
                return Ok(false)
            }
        }

        Ok(true)
    }

    fn matches_env_eq_cond(&self, data: &ConditionData<'_>) -> Result<bool> {
        if let Some(env_eq_cond) = self.env_eq.as_ref() {
            let b = env_eq_cond.iter()
                .all(|(req_env_name, req_env_val)| {
                    data.env
                        .iter()
                        .find(|(env_name, _)| env_name == req_env_name)
                        .map(|(_, env_val)| env_val == req_env_val)
                        .unwrap_or(false)
                });

            if !b {
                return Ok(false)
            }
        }

        Ok(true)
    }

    fn matches_in_image_cond(&self, data: &ConditionData<'_>) -> Result<bool> {
        if let Some(in_image_cond) = self.in_image.as_ref() {
            let b = match in_image_cond {
                OneOrMore::One(req_image) => {
                    // because the image_name in the ConditionData is Option,
                    // which is a design-decision because the image can be not-specified (in the
                    // "tree-of" subcommand),
                    // we automatically use `false` as value here.
                    //
                    // That is because if we need to have a certain image (which is what this
                    // condition expresses), and there is no image specified in the ConditionData,
                    // we are by definition are NOT in this image.
                    data.image_name
                        .as_ref()
                        .map(|i| i.as_ref() == req_image)
                        .unwrap_or(false)
                },
                OneOrMore::More(req_images) => {
                    req_images.iter()
                        .any(|ri| {
                            data.image_name
                                .as_ref()
                                .map(|inam| inam.as_ref() == ri)
                                .unwrap_or(false)
                        })
                },
            };

            Ok(b)
        } else {
            Ok(true)
        }
    }
}

/// Manual implementation of PartialOrd for Condition
///
/// Because HashMap does not implement PartialOrd
impl PartialOrd for Condition {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        use std::cmp::Ordering as O;

        let cmp_has_env = match (self.has_env.as_ref(), other.has_env.as_ref()) {
            (Some(a), Some(b)) => a.partial_cmp(b),
            (Some(_), None)    => Some(O::Greater),
            (None, Some(_))    => Some(O::Less),
            (None, None)       => Some(O::Equal),
        };

        if cmp_has_env.as_ref().map(|o| *o != O::Equal).unwrap_or(false) {
            return cmp_has_env
        }

        let cmp_env_eq = match (self.env_eq.as_ref(), other.env_eq.as_ref()) {
            // TODO: Is this safe? We ignore the HashMaps here and just say they are equal. They are most certainly not.
            (Some(_), Some(_)) => Some(O::Equal),
            (Some(_), None)    => Some(O::Greater),
            (None, Some(_))    => Some(O::Less),
            (None, None)       => Some(O::Equal),
        };

        if cmp_env_eq.as_ref().map(|o| *o != O::Equal).unwrap_or(false) {
            return cmp_env_eq
        }

        match (self.in_image.as_ref(), other.in_image.as_ref()) {
            (Some(a), Some(b)) => a.partial_cmp(b),
            (Some(_), None)    => Some(O::Greater),
            (None, Some(_))    => Some(O::Less),
            (None, None)       => Some(O::Equal),
        }
    }
}

/// Manual implementation of Ord for Condition
///
/// Because HashMap does not implement Ord
impl Ord for Condition {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.partial_cmp(other).unwrap_or(std::cmp::Ordering::Equal)
    }
}

/// Manual implementation of Hash for Condition
///
/// Because HashMap does not implement Hash
impl std::hash::Hash for Condition {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.has_env.hash(state);
        if let Some(hm) = self.env_eq.as_ref() {
            hm.iter().for_each(|(k, v)| (k, v).hash(state));
        };
        self.in_image.hash(state);
    }
}


/// Helper type for supporting Vec<T> and T in value
/// position of Condition
#[derive(Serialize, Deserialize, Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
#[serde(untagged)]
pub enum OneOrMore<T: Sized> {
    One(T),
    More(Vec<T>),
}

impl<T: Sized> Into<Vec<T>> for OneOrMore<T> {
    fn into(self) -> Vec<T> {
        match self {
            OneOrMore::One(o) => vec!