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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
use std::{
    collections::HashMap,
    path::{Path, PathBuf},
    string::ToString,
};

use containers_api::opts::{Filter, FilterItem};
use containers_api::url::encoded_pairs;
use containers_api::{
    impl_filter_func, impl_map_field, impl_opts_builder, impl_str_field, impl_url_bool_field,
    impl_url_field, impl_url_str_field,
};
use serde::Serialize;

#[derive(Clone, Serialize, Debug)]
#[serde(untagged)]
pub enum RegistryAuth {
    Password {
        username: String,
        password: String,

        #[serde(skip_serializing_if = "Option::is_none")]
        email: Option<String>,

        #[serde(rename = "serveraddress")]
        #[serde(skip_serializing_if = "Option::is_none")]
        server_address: Option<String>,
    },
    Token {
        #[serde(rename = "identitytoken")]
        identity_token: String,
    },
}

impl RegistryAuth {
    /// return a new instance with token authentication
    pub fn token<S>(token: S) -> RegistryAuth
    where
        S: Into<String>,
    {
        RegistryAuth::Token {
            identity_token: token.into(),
        }
    }

    /// return a new instance of a builder for authentication
    pub fn builder() -> RegistryAuthBuilder {
        RegistryAuthBuilder::default()
    }

    /// serialize authentication as JSON in base64
    pub fn serialize(&self) -> String {
        serde_json::to_string(self)
            .map(|c| base64::encode_config(c, base64::URL_SAFE))
            .unwrap_or_default()
    }
}

#[derive(Default)]
pub struct RegistryAuthBuilder {
    username: Option<String>,
    password: Option<String>,
    email: Option<String>,
    server_address: Option<String>,
}

impl RegistryAuthBuilder {
    /// The username used for authentication.
    pub fn username<U>(mut self, username: U) -> Self
    where
        U: Into<String>,
    {
        self.username = Some(username.into());
        self
    }

    /// The password used for authentication.
    pub fn password<P>(mut self, password: P) -> Self
    where
        P: Into<String>,
    {
        self.password = Some(password.into());
        self
    }

    /// The email addres used for authentication.
    pub fn email<E>(mut self, email: E) -> Self
    where
        E: Into<String>,
    {
        self.email = Some(email.into());
        self
    }

    /// The server address of registry, should be a domain/IP without a protocol.
    /// Example: `10.92.0.1`, `docker.corp.local`
    pub fn server_address<A>(mut self, server_address: A) -> Self
    where
        A: Into<String>,
    {
        self.server_address = Some(server_address.into());
        self
    }

    /// Create the final authentication object.
    pub fn build(&self) -> RegistryAuth {
        RegistryAuth::Password {
            username: self.username.clone().unwrap_or_default(),
            password: self.password.clone().unwrap_or_default(),
            email: self.email.clone(),
            server_address: self.server_address.clone(),
        }
    }
}

impl_opts_builder!(url => Tag);

impl TagOptsBuilder {
    impl_url_str_field!(repo => "repo");

    impl_url_str_field!(tag => "tag");
}

#[derive(Default, Debug)]
pub struct PullOpts {
    auth: Option<RegistryAuth>,
    params: HashMap<&'static str, serde_json::Value>,
}

impl PullOpts {
    /// return a new instance of a builder for Opts
    pub fn builder() -> PullOptsBuilder {
        PullOptsBuilder::default()
    }

    /// serialize Opts as a string. returns None if no Opts are defined
    pub fn serialize(&self) -> Option<String> {
        if self.params.is_empty() {
            None
        } else {
            Some(encoded_pairs(
                self.params
                    .iter()
                    .map(|(k, v)| (k, v.as_str().unwrap_or_default())),
            ))
        }
    }

    pub(crate) fn auth_header(&self) -> Option<String> {
        self.auth.clone().map(|a| a.serialize())
    }
}

pub struct PullOptsBuilder {
    auth: Option<RegistryAuth>,
    params: HashMap<&'static str, serde_json::Value>,
}

impl Default for PullOptsBuilder {
    fn default() -> Self {
        let mut params = HashMap::new();
        params.insert("tag", serde_json::Value::String("latest".into()));

        PullOptsBuilder { auth: None, params }
    }
}

impl PullOptsBuilder {
    impl_str_field!(
    /// Name of the image to pull. The name may include a tag or digest.
    /// This parameter may only be used when pulling an image.
    /// If an untagged value is provided and no `tag` is provided, _all_
    /// tags will be pulled
    /// The pull is cancelled if the HTTP connection is closed.
    image => "fromImage");

    impl_str_field!(src => "fromSrc");

    impl_str_field!(
    /// Repository name given to an image when it is imported. The repo may include a tag.
    /// This parameter may only be used when importing an image.
    /// 
    /// By default a `latest` tag is added when calling
    /// [PullOptsBuilder::default](PullOptsBuilder::default).
    repo => "repo");

    impl_str_field!(
    /// Tag or digest. If empty when pulling an image,
    /// this causes all tags for the given image to be pulled.
    tag => "tag");

    pub fn auth(mut self, auth: RegistryAuth) -> Self {
        self.auth = Some(auth);
        self
    }

    pub fn build(self) -> PullOpts {
        PullOpts {
            auth: self.auth,
            params: self.params,
        }
    }
}

#[derive(Default, Debug, Clone)]
pub struct ImageBuildOpts {
    pub path: PathBuf,
    params: HashMap<&'static str, String>,
}

impl ImageBuildOpts {
    /// return a new instance of a builder for Opts
    /// path is expected to be a file path to a directory containing a Dockerfile
    /// describing how to build a Docker image
    pub fn builder<P>(path: P) -> ImageBuildOptsBuilder
    where
        P: AsRef<Path>,
    {
        ImageBuildOptsBuilder::new(path)
    }

    /// serialize Opts as a string. returns None if no Opts are defined
    pub fn serialize(&self) -> Option<String> {
        if self.params.is_empty() {
            None
        } else {
            Some(encoded_pairs(&self.params))
        }
    }
}

#[derive(Default)]
pub struct ImageBuildOptsBuilder {
    path: PathBuf,
    params: HashMap<&'static str, String>,
}

impl ImageBuildOptsBuilder {
    /// path is expected to be a file path to a directory containing a Dockerfile
    /// describing how to build a Docker image
    pub(crate) fn new<P>(path: P) -> Self
    where
        P: AsRef<Path>,
    {
        ImageBuildOptsBuilder {
            path: path.as_ref().to_path_buf(),
            ..Default::default()
        }
    }

    impl_url_str_field!(
        /// Set the name of the docker file. defaults to `DockerFile`.
        dockerfile => "dockerfile"
    );

    impl_url_str_field!(
        /// Tag this image with a name after building it.
        tag => "t"
    );

    impl_url_str_field!(
        /// Extra hosts to add to /etc/hosts.
        extra_hosts => "extrahosts"
    );

    impl_url_str_field!(remote => "remote");

    impl_url_bool_field!(
        /// Suppress verbose build output.
        quiet => "q"
    );

    impl_url_bool_field!(
        /// Don't use the image cache when building image.
        nocahe => "nocache"
    );

    impl_url_str_field!(
        /// Attempt to pull the image even if an older image exists locally.
        pull => "pull"
    );

    impl_url_bool_field!(rm => "rm");

    impl_url_bool_field!(forcerm => "forcerm");

    impl_url_field!(
        /// Set memory limit for build.
        memory: usize => "memory"
    );

    impl_url_field!(
        /// Total memory (memory + swap). Set as -1 to disable swap.
        memswap: usize => "memswap"
    );

    impl_url_field!(
        /// CPU shares (relative weight).
        cpu_shares: usize => "cpushares"
    );

    impl_url_str_field!(
        /// CPUs in which to allow execution (eg. `0-3`, `0,1`)
        cpu_set_cpus => "cpusetcpus"
    );

    impl_url_field!(
        /// The length of a CPU period in microseconds.
        cpu_period: usize => "cpuperiod"
    );

    impl_url_field!(
        /// Microseconds of CPU time that the container can get in a CPU period.
        cpu_quota: usize => "cpuquota"
    );

    // TODO: buildargs

    impl_url_field!(
        /// Size of /dev/shm in bytes. The size must be greater than 0. If omitted the system uses 64MB.
        shm_size: usize => "shmsize"
    );

    impl_url_bool_field!(
        /// Squash the resulting images layers into a single layer. (Experimental release only.)
        squash => "squash"
    );

    // TODO: use an enum?
    impl_url_str_field!(
        /// bridge`, `host`, `none`, `container:<name|id>`, or a custom network name.
        network_mode => "networkmode"
    );

    impl_url_str_field!(
        /// Platform in the format os[/arch[/variant]].
        platform => "platform"
    );

    impl_url_str_field!(
        /// Target build stage.
        target => "target"
    );

    impl_url_str_field!(
        /// BuildKit output configuration.
        outputs => "outputs"
    );

    impl_map_field!(url
        /// Add labels to this image.
        labels => "labels"
    );

    pub fn build(&self) -> ImageBuildOpts {
        ImageBuildOpts {
            path: self.path.clone(),
            params: self.params.clone(),
        }
    }
}

/// All forms that the image identifier can take.
pub enum ImageName {
    /// `<image>[:<tag>]`
    Tag { image: String, tag: Option<String> },
    /// `<image-id>`
    Id(String),
    /// `<image@digest>`
    Digest { image: String, digest: String },
}

impl ToString for ImageName {
    fn to_string(&self) -> String {
        match &self {
            ImageName::Tag { image, tag } => match tag {
                Some(tag) => format!("{image}:{tag}"),
                None => image.to_owned(),
            },
            ImageName::Id(id) => id.to_owned(),
            ImageName::Digest { image, digest } => format!("{image}@{digest}"),
        }
    }
}

impl ImageName {
    /// Create a [`Tag`](ImageName::Tag) variant of image name.
    pub fn tag<I, T>(image: I, tag: Option<T>) -> Self
    where
        I: Into<String>,
        T: Into<String>,
    {
        Self::Tag {
            image: image.into(),
            tag: tag.map(|t| t.into()),
        }
    }

    /// Create a [`Id`](ImageName::Id) variant of image name.
    pub fn id<I>(id: I) -> Self
    where
        I: Into<String>,
    {
        Self::Id(id.into())
    }

    /// Create a [`Digest`](ImageName::Digest) variant of image name.
    pub fn digest<I, D>(image: I, digest: D) -> Self
    where
        I: Into<String>,
        D: Into<String>,
    {
        Self::Digest {
            image: image.into(),
            digest: digest.into(),
        }
    }
}

/// Filter type used to filter listed images.
pub enum ImageFilter {
    Before(ImageName),
    Dangling,
    /// Label in the form of `label=key`.
    LabelKey(String),
    /// Label in the form of `label=key=val`.
    Label(String, String),
    Since(ImageName),
    Reference(String, Option<String>),
}

impl Filter for ImageFilter {
    fn query_item(&self) -> FilterItem {
        use ImageFilter::*;
        match &self {
            Before(name) => FilterItem::new("before", name.to_string()),
            Dangling => FilterItem::new("dangling", true.to_string()),
            LabelKey(n) => FilterItem::new("label", n.to_owned()),
            Label(n, v) => FilterItem::new("label", format!("{n}={v}")),
            Since(name) => FilterItem::new("since", name.to_string()),
            Reference(image, tag) => FilterItem::new(
                "reference",
                format!(
                    "{}{}",
                    image,
                    tag.as_ref()
                        .map_or("".to_string(), |tag| format!(":{}", tag))
                ),
            ),
        }
    }
}

impl_opts_builder!(url => ImageList);

impl ImageListOptsBuilder {
    impl_url_bool_field!(
        /// Show all images. Only images from a final layer (no children) are shown by default.
        all => "all"
    );
    impl_url_bool_field!(
        /// Show digest information as a RepoDigests field on each image.
        digests => "digests"
    );
    impl_url_bool_field!(
        /// Compute and show shared size as a SharedSize field on each image.
        shared_size => "shared-size"
    );
    impl_filter_func!(
        /// Filter the listed images by one of the variants of the enum.
        ImageFilter
    );
}

impl_opts_builder!(url => ImageRemove);

impl ImageRemoveOptsBuilder {
    impl_url_bool_field!(
        /// Remove the image even if it is being used by stopped containers or has other tags.
        force => "force"
    );
    impl_url_bool_field!(
        /// Do not delete untagged parent images.
        noprune => "noprune"
    );
}

impl_opts_builder!(url => ImagePrune);

pub enum ImagesPruneFilter {
    /// When set to `true`, prune only unused and untagged images.
    /// When set to `false`, all unused images are pruned.
    Dangling(bool),
    #[cfg(feature = "chrono")]
    #[cfg_attr(docsrs, doc(cfg(feature = "chrono")))]
    /// Prune images created before this timestamp. Same as `Until` but takes a datetime object.
    UntilDate(chrono::DateTime<chrono::Utc>),
    /// Prune images created before this timestamp. The <timestamp> can be Unix timestamps,
    /// date formatted timestamps, or Go duration strings (e.g. 10m, 1h30m)
    /// computed relative to the daemon machine’s time.
    Until(String),
    /// Label in the form of `label=key`.
    LabelKey(String),
    /// Label in the form of `label=key=val`.
    Label(String, String),
}

impl Filter for ImagesPruneFilter {
    fn query_item(&self) -> FilterItem {
        use ImagesPruneFilter::*;
        match &self {
            Dangling(dangling) => FilterItem::new("dangling", dangling.to_string()),
            Until(until) => FilterItem::new("until", until.to_owned()),
            #[cfg(feature = "chrono")]
            UntilDate(until) => FilterItem::new("until", until.timestamp().to_string()),
            LabelKey(label) => FilterItem::new("label", label.to_owned()),
            Label(key, val) => FilterItem::new("label", format!("{key}={val}")),
        }
    }
}

impl ImagePruneOptsBuilder {
    impl_filter_func!(ImagesPruneFilter);
}

impl_opts_builder!(url => ClearCache);

pub enum CacheFilter {
    /// Duration relative to daemon's time, during which build cache was not used,
    /// in Go's duration format (e.g., '24h').
    Until(String),
    Id(String),
    // ID of the parent.
    Parent(String),
    Type(String),
    Description(String),
    InUse,
    Shared,
    Private,
}

impl Filter for CacheFilter {
    fn query_item(&self) -> FilterItem {
        use CacheFilter::*;
        match &self {
            Until(until) => FilterItem::new("until", until.to_owned()),
            Id(id) => FilterItem::new("id", id.to_owned()),
            Parent(parent) => FilterItem::new("parent", parent.to_owned()),
            Type(type_) => FilterItem::new("type_", type_.to_owned()),
            Description(description) => FilterItem::new("description", description.to_owned()),
            InUse => FilterItem::new("inuse", "".to_owned()),
            Shared => FilterItem::new("shared", "".to_owned()),
            Private => FilterItem::new("private", "".to_owned()),
        }
    }
}

impl ClearCacheOptsBuilder {
    impl_url_field!(
        /// Amount of disk space in bytes to keep for cache.
        keep_storage: i64 => "keep-storage"
    );
    impl_url_bool_field!(
        /// Remove all types of build cache
        all => "all"
    );
    impl_filter_func!(
        /// Filter the builder cache with variants of the enum.
        CacheFilter
    );
}

pub struct ImagePushOpts {
    auth: Option<RegistryAuth>,
    params: HashMap<&'static str, String>,
}

impl ImagePushOpts {
    pub fn builder() -> ImagePushOptsBuilder {
        ImagePushOptsBuilder::default()
    }

    pub fn serialize(&self) -> Option<String> {
        if self.params.is_empty() {
            None
        } else {
            Some(encoded_pairs(self.params.iter()))
        }
    }

    pub(crate) fn auth_header(&self) -> Option<String> {
        self.auth.clone().map(|a| a.serialize())
    }
}

pub struct ImagePushOptsBuilder {
    auth: Option<RegistryAuth>,
    params: HashMap<&'static str, String>,
}

impl Default for ImagePushOptsBuilder {
    fn default() -> Self {
        Self {
            auth: None,
            params: [("tag", "latest".into())].into(),
        }
    }
}

impl ImagePushOptsBuilder {
    impl_url_str_field!(
        /// The tag to associate with the image on the registry.
        tag => "tag"
    );

    pub fn auth(mut self, auth: RegistryAuth) -> Self {
        self.auth = Some(auth);
        self
    }

    pub fn build(self) -> ImagePushOpts {
        ImagePushOpts {
            auth: self.auth,
            params: self.params,
        }
    }
}

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

    /// Test registry auth with token
    #[test]
    fn registry_auth_token() {
        let opts = RegistryAuth::token("abc");
        assert_eq!(
            base64::encode(r#"{"identitytoken":"abc"}"#),
            opts.serialize()
        );
    }

    /// Test registry auth with username and password
    #[test]
    fn registry_auth_password_simple() {
        let opts = RegistryAuth::builder()
            .username("user_abc")
            .password("password_abc")
            .build();
        assert_eq!(
            base64::encode(r#"{"username":"user_abc","password":"password_abc"}"#),
            opts.serialize()
        );
    }

    /// Test registry auth with all fields
    #[test]
    fn registry_auth_password_all() {
        let opts = RegistryAuth::builder()
            .username("user_abc")
            .password("password_abc")
            .email("email_abc")
            .server_address("https://example.org")
            .build();
        assert_eq!(
            base64::encode(
                r#"{"username":"user_abc","password":"password_abc","email":"email_abc","serveraddress":"https://example.org"}"#
            ),
            opts.serialize()
        );
    }

    #[test]
    fn test_image_filter_reference() {
        let opts = ImageListOpts::builder()
            .filter(vec![ImageFilter::Reference("image".to_string(), None)])
            .build();
        let serialized = opts.serialize();
        assert!(serialized.is_some());
        assert_eq!(
            "filters=%7B%22reference%22%3A%5B%22image%22%5D%7D".to_string(),
            serialized.unwrap()
        );

        let opts = ImageListOpts::builder()
            .filter(vec![ImageFilter::Reference(
                "image".to_string(),
                Some("tag".to_string()),
            )])
            .build();
        let serialized = opts.serialize();
        assert!(serialized.is_some());
        assert_eq!(
            "filters=%7B%22reference%22%3A%5B%22image%3Atag%22%5D%7D".to_string(),
            serialized.unwrap()
        );
    }
}