projvar 0.19.9

A tiny CLI tool that tries to gather project specific meta-data in different ways, to store them into key=value pairs in a file for later use by other tools. See --list for the keys set by this tool.
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
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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
// SPDX-FileCopyrightText: 2021 Robin Vobruba <hoijui.quaero@gmail.com>
//
// SPDX-License-Identifier: AGPL-3.0-or-later

use std::sync::LazyLock;

use crate::license;
use crate::tools::git;
use crate::tools::git::TransferProtocol;
use crate::tools::git_hosting_provs::HostingType;
use crate::var::{Confidence, Key};
use crate::{constants, environment::Environment};
use chrono::{DateTime, NaiveDateTime};
use regex::Regex;
use thiserror::Error;
use url::Url;

pub type Result = std::result::Result<Validity, Error>;
pub type Validator = fn(&mut Environment, &str) -> Result;

// TODO Document this function! (hae... what does it do? why two confidences?)
// TODO Maybe make this use a custom struct as return instead?
#[must_use]
pub const fn res_to_confidences(res: &Result) -> [Confidence; 2] {
    match &res {
        Ok(validity) => [validity.confidence(), 0],
        Err(error) => [0, error.confidence()],
    }
}

// See these resources for implement our own, custom errors
// according to rust best practice for errors (and error handling):
// * good, simple intro:
//   <https://nick.groenen.me/posts/rust-error-handling/>
// * very nice, extensive, detailed example:
//   https://www.lpalmieri.com/posts/error-handling-rust/#removing-the-boilerplate-with-thiserror

/// This enumerates all possible errors returned by this module.
#[derive(Debug)]
pub enum Validity {
    /// The value is very valid
    High { msg: Option<String> },

    /// The value is quite valid
    Middle { msg: String },

    /// The value is just barely valid
    Low { msg: String },

    /// A non-required properties value could not be evaluated;
    /// no source returned a (valid) value for it.
    Missing,

    /// The evaluated value is usable, but with a grain of salt - be suspcious!
    Suboptimal {
        msg: String,
        source: Option<Box<dyn std::error::Error + Sync>>,
    },

    /// We have no way to check this value for validity,
    /// but at least were not able to prove it invalid.
    Unknown,
}

impl Validity {
    #[must_use]
    pub const fn confidence(&self) -> Confidence {
        match self {
            Self::High { msg: _ } => 250,
            Self::Middle { msg: _ } => 230,
            Self::Low { msg: _ } => 210,
            Self::Missing => 0,
            Self::Suboptimal { msg: _, source: _ } => 200,
            Self::Unknown => 100,
        }
    }

    /// Whether the validity indicates a value we want to use and will use for sure,
    /// if nothing better is available.
    #[must_use]
    pub const fn is_good(&self) -> bool {
        match self {
            Self::High { msg: _ } | Self::Middle { msg: _ } | Self::Low { msg: _ } => true,
            Self::Missing | Self::Suboptimal { msg: _, source: _ } | Self::Unknown => false,
        }
    }
}

/// This enumerates all possible errors returned by this module.
#[derive(Error, Debug)]
pub enum Error {
    // /// Represents an empty source. For example, an empty text file being given
    // /// as input to `count_words()`.
    // #[error("Source contains no data")]
    // EmptySource,

    // /// Represents a failure to read from input.
    // #[error("Read error")]
    // ReadError { source: std::io::Error },
    /// A required properties value could not be evaluated
    #[error("No value found for the required property {0:?}")]
    Missing(Key),

    /// The evaluated value is not usable.
    /// It make sno sense for this property as it is,
    /// but it is close to a value that would make sense,
    /// so it might contain a typo, one small part is missing or too much,
    /// or something similar.
    #[error("The value '{value}' is unfit for this key, but only just - {msg}")]
    AlmostUsableValue { msg: String, value: String }, // TODO remove value here and everywhere in this enum

    /// The evaluated value is not usable.
    /// It makes no sense for this property.
    #[error("The value '{value}' is unfit for this key - {msg}")]
    BadValue { msg: String, value: String },

    /// Represents all other cases of `std::io::Error`.
    #[error(transparent)]
    IO(#[from] std::io::Error),
}

impl Error {
    #[must_use]
    pub const fn confidence(&self) -> Confidence {
        match self {
            Self::Missing { .. } => 40,
            Self::AlmostUsableValue { .. } => 100,
            Self::BadValue { .. } => 50,
            Self::IO(_) => 30,
        }
    }
}

/// Creates a result that indicates that the given `key` is missing
fn missing(environment: &mut Environment, key: Key) -> Result {
    if environment.settings.required_keys.contains(&key) {
        Err(Error::Missing(key))
    } else {
        Ok(Validity::Missing)
    }
}

fn validate_version(environment: &mut Environment, value: &str) -> Result {
    // The official SemVer regex as of September 2021, taken from
    // https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string
    // TODO PRIO Think of what to do if we have a "v" prefix, as in "v1.2.3" -> best: remove it, but where.. a kind of pre-validator function?
    // TODO PRIO Use this create for semver checking: https://github.com/dtolnay/semver (does not need to be with a Regex!)
    static R_SEM_VERS_RELEASE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"^(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)$")
            .unwrap()
    });
    static R_SEM_VERS: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"^(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)(?:-(?P<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$").unwrap()
    });
    static R_SEM_GIT_VERS: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"^((0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*))(-(0|[1-9]\d*)-(g[0-9a-f]{7}))?((-dirty(-broken)?)|-broken(-dirty)?)?$").unwrap()
    });
    static R_GIT_VERS: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"^((g[0-9a-f]{7})|([^~^:?\[\*]+))(-(0|[1-9]\d*)-(g[0-9a-f]{7}))?((-dirty(-broken)?)|-broken(-dirty)?)?$").unwrap()
    });
    static R_GIT_SHA: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"^g?[0-9a-f]{7,40}$").unwrap());
    static R_GIT_SHA_PREFIX: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"^g[0-9a-f]{7}").unwrap());
    static R_UNKNOWN_VERS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^($|#|//)").unwrap());
    if R_SEM_VERS_RELEASE.is_match(value) {
        Ok(Validity::Low {
            msg: "This is a release version, \
which indicates either that we are on a release commit, \
or that it is imprecise, \
and actually a left-over from the previous release."
                .to_owned(),
        })
    } else if git::is_git_broken_version(value) {
        log::warn!(
            "Broken project version '{value}'; something is seriously wrong with your git repo"
        );
        Ok(Validity::Suboptimal {
            msg: "This version is broken; something is seriously wrong with your git repo."
                .to_owned(),
            source: None,
        })
    } else if git::is_git_dirty_version(value) {
        log::warn!("Dirty project version '{value}'; you have uncommitted changes in your project");
        if R_GIT_SHA_PREFIX.is_match(value) {
            Ok(Validity::Low {
                msg: "This version is technically ok - \
having a raw git SHA as base - \
but not a release-version, \
and not human-readable; \
it does not allow direct comparison with other versions.
We trust it because it is dirty, though."
                    .to_owned(),
            })
        } else {
            Ok(Validity::Middle {
                msg: "A git dirty version starting with a tag".to_owned(),
            })
        }
    } else if R_SEM_VERS.is_match(value) {
        // This version is (git-)technically good,
        // but not a release-version
        // (i.e., does not look so nice).
        Ok(Validity::Middle {
            msg: "semver".to_owned(),
        })
    } else if R_GIT_SHA.is_match(value) {
        Ok(Validity::Suboptimal {
            msg: "This version is technically ok - \
a raw git SHA - \
but not a release-version, \
and not human-readable; \
it does not allow direct comparison with other versions."
                .to_owned(),
            source: None,
        })
    } else if R_SEM_GIT_VERS.is_match(value) {
        // This version is (git-)technically good,
        // but not a release-version,
        // and not a valid semver.
        // It has a semver release versaion as a base,
        // and is a valid git version, as a whole.
        // (i.e., does not look so nice).
        Ok(Validity::Middle {
            msg: "A git version starting with a semver tag, \
but not a valid semver version"
                .to_owned(),
        })
    } else if R_GIT_VERS.is_match(value) {
        // This version is (git-)technically good,
        // but not commonly accepted as a release-version,
        // as it is not semver.
        match R_GIT_SHA_PREFIX.find(value) {
            Some(mtch) if mtch.range().len() == value.len() => Ok(Validity::Suboptimal {
                msg: "This version (a git SHA) is technically ok, \
but not a release-version, and not human-readable"
                    .to_owned(),
                source: None,
            }),
            Some(_) => Ok(Validity::Suboptimal {
                msg: "A git version starting with a SHA \
(instead of a (semver-)tag, which would be preffered)"
                    .to_owned(),
                source: None,
            }),
            None => {
                // It is a detailed git version, starting with a tag
                Ok(Validity::Low {
                    msg: "A git version starting with/consisting of a non-semver tag".to_owned(),
                })
            }
        }
    } else if R_UNKNOWN_VERS.is_match(value) {
        missing(environment, Key::Version)
    } else {
        Err(Error::BadValue {
            msg: "Not a valid version".to_owned(),
            value: value.to_owned(),
        })
    }
}

fn validate_license(environment: &mut Environment, value: &str) -> Result {
    if value.is_empty() {
        missing(environment, Key::License)
    } else {
        license::validate_spdx_expr(value).map_or_else(
            |err| {
                match err {
                    license::Error::NoLicense => Ok(Validity::Suboptimal {
                        msg: "Not a recognized SPDX license identifier".to_owned(),
                        source: Some(Box::new(err)),
                    }),
                    license::Error::ParsingFailed(_) => Ok(Validity::Suboptimal {
                        msg: "Not a valid SPDX license expression".to_owned(),
                        source: Some(Box::new(err)),
                    }),
                    license::Error::NotApproved(_) => Ok(Validity::Low {
                        // TODO We are loosing the detailed info here!
                        msg: "Not only approved licenses".to_owned(),
                    }),
                }
            },
            |()| {
                Ok(Validity::High {
                    msg: Some("Consists of an SPDX license identifier".to_owned()),
                })
            },
        )
    }
}

fn validate_licenses(environment: &mut Environment, value: &str) -> Result {
    if value.is_empty() {
        missing(environment, Key::Licenses)
    } else {
        // TODO PRIO Implement SPDX expressions detection, not just (as is now) single identifiers; see: TODO
        for license in value.split(',') {
            let license = license.trim();
            let res = validate_license(environment, license);
            if let Err(err) = res {
                return Ok(Validity::Suboptimal {
                    msg: format!(
                        "Not all of these are recognized SPDX license identifiers: {value}\n\tspecifically '{license}'",
                    ),
                    source: Some(Box::new(err)),
                });
            }
        }
        Ok(Validity::High {
            msg: Some(
                "Consists of a list of SPDX license identifiers, separated by ','".to_owned(),
            ),
        })
    }
}

fn check_public_url(
    _environment: &mut Environment,
    value: &str,
    allow_ssh: bool,
    allow_git: bool,
) -> std::result::Result<Url, Error> {
    match Url::parse(value) {
        Err(_err) => Err(Error::BadValue {
            msg: "Not a valid URL".to_owned(),
            value: value.to_owned(),
        }),
        Ok(url) => {
            let mut valid_schemes = vec!["http", "https"];
            if allow_ssh {
                valid_schemes.push("ssh");
            }
            if allow_git {
                valid_schemes.push("git");
            }
            if !valid_schemes.contains(&url.scheme()) {
                Err(Error::AlmostUsableValue {
                    msg: format!(
                        "Should use one of these as protocol(scheme): [{}]",
                        valid_schemes.join(", ")
                    ),
                    value: value.to_owned(),
                })
            } else if url.username() != "" && url.username() != "git" {
                Err(Error::AlmostUsableValue {
                    msg: format!(
                        "Should be anonymous access, but specifies a user-name: {}",
                        url.username()
                    ),
                    value: value.to_owned(),
                })
            } else if let Some(_pw) = url.password() {
                Err(Error::AlmostUsableValue {
                    msg: "Should be anonymous access, but contains a password".to_owned(),
                    value: value.to_owned(),
                })
            } else if let Some(query) = url.query() {
                Err(Error::AlmostUsableValue {
                    msg: format!("Should be a simple URL, but uses query arguments: {query}",),
                    value: value.to_owned(),
                })
            } else if let Some(fragment) = url.fragment() {
                Err(Error::AlmostUsableValue {
                    msg: format!("Should be a simple URL, but uses a fragment: {fragment}"),
                    value: value.to_owned(),
                })
            } else {
                Ok(url)
            }
        }
    }
}

fn check_empty(_environment: &mut Environment, value: &str, part_desc: &str) -> Result {
    if value.is_empty() {
        Err(Error::BadValue {
            msg: format!("{part_desc} can not be empty"),
            value: value.to_owned(),
        })
    } else {
        Ok(Validity::Low {
            msg: "at least not empty".to_owned(),
        })
    }
}

fn eval_hosting_type(environment: &Environment, url: &Url) -> HostingType {
    // manually "inline" this function (as in: get rid of it)
    environment.settings.hosting_type(url)
}

fn eval_hosting_type_from_hosting_suffix(environment: &mut Environment, url: &Url) -> HostingType {
    // manually "inline" this function (as in: get rid of it)
    environment.settings.hosting_type_from_hosting_suffix(url)
}

fn check_url_path(value: &str, url_desc: &str, url: &Url, path_reg: Option<&Regex>) -> Result {
    if let (Some(path_reg), Some(host)) = (path_reg, url.host().as_ref()) {
        if path_reg.is_match(url.path()) {
            Ok(Validity::High {
                msg: Some(format!(
                    r#"For {}, the path part of the {} URL ("{}") matches regex "{}""#,
                    host,
                    url_desc,
                    url.path(),
                    path_reg.as_str()
                )),
            })
        } else {
            Err(Error::AlmostUsableValue {
                msg: format!(
                    r#"For {}, this path part of the {} URL is invalid: "{}"; it should match "{}""#,
                    host,
                    url_desc,
                    url.path(),
                    path_reg.as_str()
                ),
                value: value.to_owned(),
            })
        }
    } else {
        Ok(Validity::Unknown)
    }
}

fn check_url_host(value: &str, url_desc: &str, url: &Url, host_reg: Option<&Regex>) -> Result {
    if let (Some(host_reg), Some(host)) = (host_reg, url.host().as_ref()) {
        let host_str = host.to_string();
        if host_reg.is_match(&host_str) {
            Ok(Validity::High {
                msg: Some(format!(
                    r#"For {}, the host part of the {} URL ("{}") matches regex "{}""#,
                    host,
                    url_desc,
                    host_str,
                    host_reg.as_str()
                )),
            })
        } else {
            Err(Error::AlmostUsableValue {
                msg: format!(
                    r#"For {}, this host part of the {} URL is invalid: "{}"; it should match "{}""#,
                    host,
                    url_desc,
                    host_str,
                    host_reg.as_str()
                ),
                value: value.to_owned(),
            })
        }
    } else {
        Ok(Validity::Unknown)
    }
}

fn validate_repo_web_url(environment: &mut Environment, value: &str) -> Result {
    static R_GIT_HUB_PATH: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"^/(?P<user>[^/]+)/(?P<repo>[^/]+)/?$").unwrap());
    static R_GIT_LAB_PATH: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"^/(?P<user>[^/]+)/((?P<structure>[^/]+)/)*(?P<repo>[^/]+)/?$").unwrap()
    });
    static R_BIT_BUCKET_PATH: LazyLock<Regex> = LazyLock::new(|| (*R_GIT_HUB_PATH).clone());

    let url = check_public_url(environment, value, false, false)?;
    let hosting_type = eval_hosting_type(environment, &url);
    let host_reg: Option<&Regex> = match hosting_type {
        HostingType::GitHub => Some(&R_GIT_HUB_PATH),
        HostingType::GitLab => Some(&R_GIT_LAB_PATH),
        HostingType::BitBucket => Some(&R_BIT_BUCKET_PATH),
        _ => None, // TODO Implement the others
    };
    check_url_path(value, "versioned web", &url, host_reg)
}

static R_GIT_HUB_CLONE_PATH: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^/(?P<user>[^/]+)/(?P<repo>[^/]+)(\.git)?$").unwrap());
static R_GIT_LAB_CLONE_PATH: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^/(?P<user>[^/]+)/((?P<structure>[^/]+)/)*(?P<repo>[^/]+)(\.git)?$").unwrap()
});
static R_BIT_BUCKET_CLONE_PATH: LazyLock<Regex> = LazyLock::new(|| (*R_GIT_HUB_CLONE_PATH).clone());

/// Many possible formats, see:
/// * <https://www.git-scm.com/docs/git-clone#_git_urls>
/// * <https://github.com/tjtelan/git-url-parse-rs>
/// * <https://github.com/Byron/gitoxide/blob/main/git-url>
/// * <>
fn validate_repo_clone_url(_environment: &mut Environment, value: &str) -> Result {
    gix_url::parse(value.into())
        .map(|_url| Validity::Middle {
            msg:
                "Nothing wrong with that; but we can/do not check more than that it is a valid URL"
                    .to_owned(),
        })
        .map_err(|err| Error::BadValue {
            msg: err.to_string(),
            value: value.to_owned(),
        })
}

fn validate_repo_clone_url_generic(
    environment: &mut Environment,
    value: &str,
    protocol: TransferProtocol,
) -> Result {
    let url = check_public_url(
        environment,
        value,
        matches!(protocol, TransferProtocol::Ssh),
        matches!(protocol, TransferProtocol::Git),
    )?;
    if url.scheme() != protocol.scheme_str() {
        return Err(Error::BadValue {
            msg: format!(
                "Wrong URL Scheme; should be '{}', but is '{}'",
                protocol.scheme_str(),
                url.scheme()
            ),
            value: value.to_owned(),
        });
    }
    let hosting_type = eval_hosting_type(environment, &url);
    let host_reg: Option<&Regex> = match hosting_type {
        HostingType::GitHub => Some(&R_GIT_HUB_CLONE_PATH),
        HostingType::GitLab => Some(&R_GIT_LAB_CLONE_PATH),
        HostingType::BitBucket => Some(&R_BIT_BUCKET_CLONE_PATH),
        _ => None, // TODO Implement the others
    };
    check_url_path(value, "repo clone", &url, host_reg)
}

// * git://repo.or.cz/girocco.git
fn validate_repo_clone_url_git(environment: &mut Environment, value: &str) -> Result {
    validate_repo_clone_url_generic(environment, value, TransferProtocol::Git)
}

// * https://git@bitbucket.org/Aouatef/master_arbeit.git
fn validate_repo_clone_url_http(environment: &mut Environment, value: &str) -> Result {
    validate_repo_clone_url_generic(environment, value, TransferProtocol::Https)
}

// * git@bitbucket.org:Aouatef/master_arbeit.git
// * ssh://bitbucket.org/Aouatef/master_arbeit.git
fn validate_repo_clone_url_ssh(environment: &mut Environment, value: &str) -> Result {
    // NOTE We only accept the user "git", as it stands for anonymous access
    static R_SSH_CLONE_URL: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"^(?P<user>git@)?(?P<host>[^/:]+)((:|/)(?P<path>.+))?$").unwrap()
    });

    let url = match check_public_url(environment, value, true, false) {
        Ok(url) => {
            if url.scheme() != TransferProtocol::Ssh.scheme_str() {
                return Err(Error::AlmostUsableValue {
                    msg: format!(
                        "Wrong URL Scheme; should be '{}', but is '{}'",
                        TransferProtocol::Ssh.scheme_str(),
                        url.scheme()
                    ),
                    value: value.to_owned(),
                });
            }
            url
        }
        Err(err_orig) => {
            let ssh_value = R_SSH_CLONE_URL.replace(value, "ssh://$host/$path");
            match check_public_url(environment, &ssh_value, true, false) {
                Ok(url) => url,
                // If also the ssh_value failed to parse,
                // return the error concerning the failed parsing of the original value.
                Err(_err_ssh) => return Err(err_orig), // Err(_err_ssh) => return Err(_err_ssh),
            }
        }
    };

    let hosting_type = eval_hosting_type(environment, &url);
    let host_reg: Option<&Regex> = match hosting_type {
        HostingType::GitHub => Some(&R_GIT_HUB_CLONE_PATH),
        HostingType::GitLab => Some(&R_GIT_LAB_CLONE_PATH),
        HostingType::BitBucket => Some(&R_BIT_BUCKET_CLONE_PATH),
        _ => None, // TODO Implement the others
    };
    check_url_path(value, "repo clone ssh", &url, host_reg)
}

/// See also `sources::try_construct_raw_prefix_url`.
// * https://raw.githubusercontent.com/hoijui/nim-ci/master/.github/workflows/docker.yml
// * https://gitlab.com/OSEGermany/osh-tool/-/raw/master/data/source_extension_formats.csv
// * https://gitlab.com/OSEGermany/osh-tool/raw/master/data/source_extension_formats.csv
// * https://bitbucket.org/Aouatef/master_arbeit/raw/ae4a42a850b359a23da2483eb8f867f21c5382d4/procExData/import.sh
fn validate_repo_raw_versioned_prefix_url(environment: &mut Environment, value: &str) -> Result {
    static R_GIT_HUB_PATH: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"^/(?P<user>[^/]+)/(?P<repo>[^/]+)$").unwrap());
    static R_GIT_LAB_PATH: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"^/(?P<user>[^/]+)/((?P<structure>[^/]+)/)*(?P<repo>[^/]+)/(-/)?raw$").unwrap()
    });
    static R_BIT_BUCKET_PATH: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"^/(?P<user>[^/]+)/(?P<repo>[^/]+)/raw$").unwrap());

    let url = check_public_url(environment, value, false, false)?;
    let hosting_type = eval_hosting_type(environment, &url);
    let host_reg: Option<&Regex> = match hosting_type {
        HostingType::GitHub => Some(&R_GIT_HUB_PATH),
        HostingType::GitLab => Some(&R_GIT_LAB_PATH),
        HostingType::BitBucket => Some(&R_BIT_BUCKET_PATH),
        _ => None, // TODO Implement the others
    };
    check_url_path(value, "raw versioned prefix", &url, host_reg)
}

/// See also `sources::try_construct_file_prefix_url`.
fn validate_repo_versioned_file_prefix_url(environment: &mut Environment, value: &str) -> Result {
    static R_GIT_HUB_PATH: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"^/(?P<user>[^/]+)/(?P<repo>[^/]+)/blob$").unwrap());
    static R_GIT_LAB_PATH: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"^/(?P<user>[^/]+)/((?P<structure>[^/]+)/)*(?P<repo>[^/]+)/(-/)?blob$").unwrap()
    });
    static R_BIT_BUCKET_PATH: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"^/(?P<user>[^/]+)/(?P<repo>[^/]+)/src$").unwrap());

    let url = check_public_url(environment, value, false, false)?;
    let hosting_type = eval_hosting_type(environment, &url);
    let host_reg: Option<&Regex> = match hosting_type {
        HostingType::GitHub => Some(&R_GIT_HUB_PATH),
        HostingType::GitLab => Some(&R_GIT_LAB_PATH),
        HostingType::BitBucket => Some(&R_BIT_BUCKET_PATH),
        _ => None, // TODO Implement the others
    };
    check_url_path(value, "versioned file prefix", &url, host_reg)
}

/// See also `sources::try_construct_file_prefix_url`.
fn validate_repo_versioned_dir_prefix_url(environment: &mut Environment, value: &str) -> Result {
    static R_GIT_HUB_PATH: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"^/(?P<user>[^/]+)/(?P<repo>[^/]+)/tree$").unwrap());
    static R_GIT_LAB_PATH: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"^/(?P<user>[^/]+)/((?P<structure>[^/]+)/)*(?P<repo>[^/]+)/(-/)?tree$").unwrap()
    });
    static R_BIT_BUCKET_PATH: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"^/(?P<user>[^/]+)/(?P<repo>[^/]+)/src$").unwrap());

    let url = check_public_url(environment, value, false, false)?;
    let hosting_type = eval_hosting_type(environment, &url);
    let host_reg: Option<&Regex> = match hosting_type {
        HostingType::GitHub => Some(&R_GIT_HUB_PATH),
        HostingType::GitLab => Some(&R_GIT_LAB_PATH),
        HostingType::BitBucket => Some(&R_BIT_BUCKET_PATH),
        _ => None, // TODO Implement the others
    };
    check_url_path(value, "versioned dir prefix", &url, host_reg)
}

/// See also `sources::try_construct_commit_prefix_url`.
fn validate_repo_commit_prefix_url(environment: &mut Environment, value: &str) -> Result {
    static R_GIT_HUB_PATH: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"^/(?P<user>[^/]+)/(?P<repo>[^/]+)/commit$").unwrap());
    static R_GIT_LAB_PATH: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"^/(?P<user>[^/]+)/((?P<structure>[^/]+)/)*(?P<repo>[^/]+)/(-/)?commit$")
            .unwrap()
    });
    static R_BIT_BUCKET_PATH: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"^/(?P<user>[^/]+)/(?P<repo>[^/]+)/commits$").unwrap());

    let url = check_public_url(environment, value, false, false)?;
    let hosting_type = eval_hosting_type(environment, &url);
    let host_reg: Option<&Regex> = match hosting_type {
        HostingType::GitHub => Some(&R_GIT_HUB_PATH),
        HostingType::GitLab => Some(&R_GIT_LAB_PATH),
        HostingType::BitBucket => Some(&R_BIT_BUCKET_PATH),
        _ => None, // TODO Implement the others
    };
    check_url_path(value, "commit prefix", &url, host_reg)
}

fn validate_repo_issues_url(environment: &mut Environment, value: &str) -> Result {
    static R_GIT_HUB_PATH: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"^/(?P<user>[^/]+)/(?P<repo>[^/]+)/issues$").unwrap());
    static R_GIT_LAB_PATH: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"^/(?P<user>[^/]+)/((?P<structure>[^/]+)/)*(?P<repo>[^/]+)/(-/)?issues$")
            .unwrap()
    });
    static R_BIT_BUCKET_PATH: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"^/(?P<user>[^/]+)/(?P<repo>[^/]+)/issues$").unwrap());

    let url = check_public_url(environment, value, false, false)?;
    let hosting_type = eval_hosting_type(environment, &url);
    let host_reg: Option<&Regex> = match hosting_type {
        HostingType::GitHub => Some(&R_GIT_HUB_PATH),
        HostingType::GitLab => Some(&R_GIT_LAB_PATH),
        HostingType::BitBucket => Some(&R_BIT_BUCKET_PATH),
        _ => None, // TODO Implement the others
    };
    check_url_path(value, "issues", &url, host_reg)
}

fn validate_build_hosting_url(environment: &mut Environment, value: &str) -> Result {
    static R_GIT_HUB_HOST: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"^(?P<user>[^/.]+)\.github\.io$").unwrap());
    static R_GIT_LAB_HOST: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"^(?P<user>[^/.]+)\.gitlab\.io$").unwrap());
    // NOTE BitBucket does not have this feature, it only supports one "page" repo per user, not per repo

    let url = check_public_url(environment, value, false, false)?;
    let hosting_type = eval_hosting_type_from_hosting_suffix(environment, &url);
    let host_reg: Option<&Regex> = match hosting_type {
        HostingType::GitHub => Some(&R_GIT_HUB_HOST),
        HostingType::GitLab => Some(&R_GIT_LAB_HOST),
        _ => None, // TODO Implement the others (BitBucket does not have pages though, so skip it!)
    };
    check_url_host(value, "build hosting", &url, host_reg)
}

fn validate_name(environment: &mut Environment, value: &str) -> Result {
    check_empty(environment, value, "Project name (human-readable)")
}

fn validate_name_machine_readable(environment: &mut Environment, value: &str) -> Result {
    static R_MACHINE_READABLE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"^[0-9a-zA-Z_-]+$").unwrap());

    check_empty(environment, value, "Project name (machine-readable)")?;
    if R_MACHINE_READABLE.is_match(value) {
        Ok(Validity::High {
            msg: Some(format!("Matches regex '{}'", R_MACHINE_READABLE.as_str())),
        })
    } else {
        Err(Error::BadValue {
            msg: format!(
                "Name is not machine-readable, does not match '{}'",
                R_MACHINE_READABLE.as_str()
            ),
            value: value.to_owned(),
        })
    }
}

fn check_date(environment: &mut Environment, value: &str, date_desc: &str) -> Result {
    if value.is_empty() {
        return Err(Error::BadValue {
            // TODO Maybe replace with a call to missing(...) ?
            msg: format!("{date_desc} date can not be empty"),
            value: value.to_owned(),
        });
    }

    let parse_err = NaiveDateTime::parse_from_str(value, &environment.settings.date_format)
        .err()
        .and_then(|_err| DateTime::parse_from_str(value, &environment.settings.date_format).err());
    if let Some(err) = parse_err {
        // log::error!("XXX {}", NaiveDateTime::parse_from_str(value, &environment.settings.date_format).unwrap_err());
        Err(Error::BadValue {
            msg: format!(
                r#"Not a {} date according to the date-format "{}": {}"#,
                date_desc, environment.settings.date_format, err
            ),
            value: value.to_owned(),
        })
    } else {
        Ok(Validity::High {
            msg: Some(format!(
                "Matches the date format '{}'",
                environment.settings.date_format
            )),
        })
    }
}

fn validate_version_date(environment: &mut Environment, value: &str) -> Result {
    check_date(environment, value, "version")
}

fn validate_build_date(environment: &mut Environment, value: &str) -> Result {
    check_date(environment, value, "build")
}

fn validate_build_branch(environment: &mut Environment, value: &str) -> Result {
    check_empty(environment, value, "Branch")
}

fn validate_build_tag(environment: &mut Environment, value: &str) -> Result {
    check_empty(environment, value, "Tag")
}

fn validate_build_os(environment: &mut Environment, value: &str) -> Result {
    check_empty(environment, value, "Build OS") // TODO Maybe add a list of known good (just like for OsFamily), and mark the others as Ok(Validity::Unknown)
}

fn validate_build_os_family(environment: &mut Environment, value: &str) -> Result {
    check_empty(environment, value, "Build OS Family")?;
    if constants::VALID_OS_FAMILIES.contains(&value) {
        Ok(Validity::High { msg: None })
    } else {
        // todo!();
        // Err(Error::SuboptimalValue {
        //     msg: "TODO".to_owned(), // TODO
        //     value: value.to_owned(),
        // })
        Err(Error::BadValue {
            msg: format!(
                "Only these values are valid: {}",
                constants::VALID_OS_FAMILIES.join(", ")
            ),
            value: value.to_owned(),
        })
    }
}

fn validate_build_arch(environment: &mut Environment, value: &str) -> Result {
    check_empty(environment, value, "Build arch")?;
    if constants::VALID_ARCHS.contains(&value) {
        Ok(Validity::High { msg: None })
    } else {
        // todo!();
        // Err(Error::SuboptimalValue {
        //     msg: "TODO".to_owned(), // TODO
        //     value: value.to_owned(),
        // })
        Err(Error::BadValue {
            msg: format!(
                "Only these values are valid: {}",
                constants::VALID_ARCHS.join(", ")
            ),
            value: value.to_owned(),
        })
    }
}

fn validate_build_number(environment: &mut Environment, value: &str) -> Result {
    check_empty(environment, value, "Build number")?;
    match value.parse::<i32>() {
        Err(_err) => Ok(Validity::Suboptimal {
            msg: "It is generally recommended and assumed that the build number is an integer (a positive, whole number)".to_owned(),
            source: None,
        }),
        Ok(_int_value) => Ok(Validity::High { msg: Some("Is a build number (positive integer)".to_owned()) })
    }
}

fn validate_ci(environment: &mut Environment, value: &str) -> Result {
    check_empty(environment, value, "CI")?;
    match value {
        "true" => Ok(Validity::High { msg: None }),
        "false" => Ok(Validity::Middle {
            msg: "Nothing wrong with that, but any 'true' value will get prefference over 'false'"
                .to_owned(),
        }),
        &_ => Err(Error::BadValue {
            msg:
                r"CI can be 'true', 'false' or be ommitted (None), which get interpreted as 'false'"
                    .to_owned(),
            value: value.to_owned(),
        }),
    }
}

#[remain::check]
#[must_use]
pub fn get(key: Key) -> Validator {
    // TODO This match could be written by a macro
    #[remain::sorted]
    match key {
        Key::BuildArch => validate_build_arch,
        Key::BuildBranch => validate_build_branch,
        Key::BuildDate => validate_build_date,
        Key::BuildHostingUrl => validate_build_hosting_url,
        Key::BuildNumber => validate_build_number,
        Key::BuildOs => validate_build_os,
        Key::BuildOsFamily => validate_build_os_family,
        Key::BuildTag => validate_build_tag,
        Key::Ci => validate_ci,
        Key::License => validate_license,
        Key::Licenses => validate_licenses,
        Key::Name => validate_name,
        Key::NameMachineReadable => validate_name_machine_readable,
        Key::RepoCloneUrl => validate_repo_clone_url,
        Key::RepoCloneUrlGit => validate_repo_clone_url_git,
        Key::RepoCloneUrlHttp => validate_repo_clone_url_http,
        Key::RepoCloneUrlSsh => validate_repo_clone_url_ssh,
        Key::RepoCommitPrefixUrl => validate_repo_commit_prefix_url,
        Key::RepoIssuesUrl => validate_repo_issues_url,
        Key::RepoRawVersionedPrefixUrl => validate_repo_raw_versioned_prefix_url,
        Key::RepoVersionedDirPrefixUrl => validate_repo_versioned_dir_prefix_url,
        Key::RepoVersionedFilePrefixUrl => validate_repo_versioned_file_prefix_url,
        Key::RepoWebUrl => validate_repo_web_url,
        Key::Version => validate_version,
        Key::VersionDate => validate_version_date,
    }
}

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

    // %Y-%m-%d %H:%M:%S\"", value: "2021-09-21 06:27:37
    // #[test]
    // fn date_time() -> Result<(), chrono::ParseError> {

    //     let custom = DateTime::parse_from_str("2021-09-21 06:27:37", "%Y-%m-%d %H:%M:%S")?;
    //     println!("{}", custom);
    //     let custom = chrono::NaiveDateTime::parse_from_str("2021-09-21 06:27:37", "%Y-%m-%d %H:%M:%S")?;
    //     println!("{}", custom);

    //     Ok(())
    // }

    fn is_good(res: Result) -> bool {
        if let Ok(val) = res {
            val.is_good()
        } else {
            false
        }
    }

    fn is_high(res: Result) -> bool {
        if let Ok(val) = res {
            matches!(&val, &Validity::High { .. })
        } else {
            false
        }
    }

    fn is_middle(res: Result) -> bool {
        if let Ok(val) = res {
            matches!(&val, &Validity::Middle { .. })
        } else {
            false
        }
    }

    fn is_low(res: Result) -> bool {
        if let Ok(val) = res {
            matches!(&val, &Validity::Low { .. })
        } else {
            false
        }
    }

    fn is_suboptimal(res: Result) -> bool {
        if let Ok(val) = res {
            matches!(&val, &Validity::Suboptimal { .. })
        } else {
            false
        }
    }

    fn is_missing_err(res: Result) -> bool {
        if let Err(err) = res {
            matches!(&err, &Error::Missing { .. })
        } else {
            false
        }
    }

    fn is_bad_value(res: Result) -> bool {
        if let Err(err) = res {
            matches!(&err, &Error::BadValue { .. })
        } else {
            false
        }
    }

    #[test]
    fn test_validate_version() {
        let mut environment = Environment::stub();
        let full_sha = "cf73ea34fcc785b1ac44ffb20d655c917e77c83d";

        // Good cases
        for sha_length in 7..full_sha.len() {
            assert!(is_suboptimal(validate_version(
                &mut environment,
                &full_sha[0..sha_length],
            )));
        }
        assert!(is_suboptimal(validate_version(
            &mut environment,
            "gad8f844"
        )));
        assert!(is_low(validate_version(&mut environment, "gad8f844-dirty")));
        assert!(is_suboptimal(validate_version(
            &mut environment,
            "gad8f844-broken"
        )));
        assert!(is_suboptimal(validate_version(
            &mut environment,
            "gad8f844-dirty-broken"
        )));
        assert!(is_suboptimal(validate_version(
            &mut environment,
            "gad8f844-broken-dirty"
        )));
        assert!(is_middle(validate_version(
            &mut environment,
            "0.1.19-12-gad8f844"
        )));
        assert!(is_middle(validate_version(
            &mut environment,
            "0.1.19-12-gad8f844-dirty"
        )));
        assert!(is_suboptimal(validate_version(
            &mut environment,
            "0.1.19-12-gad8f844-broken"
        )));
        assert!(is_suboptimal(validate_version(
            &mut environment,
            "0.1.19-12-gad8f844-dirty-broken"
        )));
        assert!(is_suboptimal(validate_version(
            &mut environment,
            "0.1.19-12-gad8f844-broken-dirty"
        )));
        assert!(is_good(validate_version(&mut environment, "0.1.19")));
        assert!(is_middle(validate_version(
            &mut environment,
            "0.1.19-dirty"
        )));
        assert!(is_suboptimal(validate_version(
            &mut environment,
            "0.1.19-broken"
        )));
        assert!(is_suboptimal(validate_version(
            &mut environment,
            "0.1.19-dirty-broken"
        )));
        assert!(is_suboptimal(validate_version(
            &mut environment,
            "0.1.19-broken-dirty"
        )));

        // Bad cases
        assert!(is_missing_err(validate_version(&mut environment, "")));
        assert!(is_low(validate_version(&mut environment, "gabcdefg")));
        assert!(is_low(validate_version(
            &mut environment,
            "din-spec-3105-0.10.0-202-g9b5ff47"
        )));
        // TODO Add some more bad cases. producing various different errors
    }

    #[test]
    fn test_validate_license() {
        let mut environment = Environment::stub();
        assert!(is_good(validate_license(&mut environment, "GPL-3.0")));
        assert!(is_high(validate_license(&mut environment, "GPL-3.0")));
        assert!(is_good(validate_license(
            &mut environment,
            "GPL-3.0-or-later"
        )));
        assert!(is_good(validate_license(&mut environment, "GPL-2.0")));
        assert!(is_good(validate_license(
            &mut environment,
            "GPL-2.0-or-later"
        )));
        assert!(is_good(validate_license(&mut environment, "AGPL-3.0")));
        assert!(is_good(validate_license(
            &mut environment,
            "AGPL-3.0-or-later"
        )));
        assert!(is_good(validate_license(&mut environment, "CC0-1.0")));
        assert!(is_low(validate_license(&mut environment, "CC0-1.0")));
        assert!(is_suboptimal(validate_license(&mut environment, "CC0-2.0")));
        assert!(is_suboptimal(validate_license(&mut environment, "CC02.0")));
        assert!(is_suboptimal(validate_license(&mut environment, "GPL")));
        assert!(is_suboptimal(validate_license(&mut environment, "AGPL")));
        assert!(is_suboptimal(validate_license(
            &mut environment,
            "Some Unknown License"
        )));
        assert!(is_missing_err(validate_license(&mut environment, "")));
        // todo!(); // TODO Add some more bad cases; Producing different errors
    }

    #[test]
    fn test_validate_repo_versioned_dir_prefix_url() -> std::result::Result<(), Error> {
        let mut environment = Environment::stub();
        // assert!(validate_repo_versioned_web_url(&mut environment, "https://github.com/hoijui/projvar/tree/525b3c9b8962dd02aab6ea867eebdee3719a6634")?.is_ok());
        validate_repo_versioned_dir_prefix_url(
            &mut environment,
            "https://github.com/hoijui/projvar/tree",
        )?;
        Ok(())
    }
}