winget-types 0.4.3

WinGet Types
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
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
#![expect(clippy::struct_excessive_bools)]

mod apps_and_features_entries;
mod architecture;
pub mod authentication;
mod capability;
mod channel;
mod command;
mod dependencies;
mod elevation_requirement;
mod expected_return_codes;
mod file_extension;
mod install_modes;
mod installation_metadata;
mod installer_return_code;
mod installer_type;
mod market;
mod minimum_os_version;
mod nested;
mod platform;
mod protocol;
mod repair_behavior;
mod return_response;
mod scope;
pub mod switches;
mod unsupported_arguments;
mod unsupported_os_architectures;
mod upgrade_behavior;

use alloc::{collections::BTreeSet, string::String, vec::Vec};

pub use apps_and_features_entries::{AppsAndFeaturesEntries, AppsAndFeaturesEntry};
pub use architecture::{Architecture, ParseArchitectureError};
pub use authentication::Authentication;
pub use capability::{Capability, CapabilityError, RestrictedCapability};
pub use channel::{Channel, ChannelError};
pub use command::{Command, CommandError};
pub use dependencies::{Dependencies, PackageDependencies};
pub use elevation_requirement::ElevationRequirement;
pub use expected_return_codes::ExpectedReturnCodes;
pub use file_extension::{FileExtension, FileExtensionError};
pub use install_modes::InstallModes;
pub use installation_metadata::InstallationMetadata;
pub use installer_return_code::{InstallerReturnCode, InstallerSuccessCode};
pub use installer_type::InstallerType;
use itertools::Itertools;
pub use market::{Market, MarketError, Markets, MarketsError};
pub use minimum_os_version::{MinimumOSVersion, MinimumOSVersionError};
use nested::installer_type::NestedInstallerType;
pub use nested::{
    PortableCommandAlias, PortableCommandAliasError, installer_files::NestedInstallerFiles,
};
pub use package_family_name::PackageFamilyName;
pub use platform::{Platform, PlatformParseError};
pub use protocol::{Protocol, ProtocolError};
pub use repair_behavior::RepairBehavior;
pub use return_response::ReturnResponse;
pub use scope::{Scope, ScopeParseError};
pub use switches::InstallerSwitches;
pub use unsupported_arguments::UnsupportedArguments;
pub use unsupported_os_architectures::UnsupportedOSArchitecture;
pub use upgrade_behavior::{UpgradeBehavior, UpgradeBehaviorParseError};

use super::{
    LanguageTag, Manifest, ManifestType, ManifestVersion, PackageIdentifier, PackageVersion,
    Sha256String, url::DecodedUrl,
};

pub const VALID_FILE_EXTENSIONS: [&str; 7] = [
    "msix",
    "msi",
    "appx",
    "exe",
    "zip",
    "msixbundle",
    "appxbundle",
];

#[cfg(feature = "chrono")]
type Date = chrono::NaiveDate;

#[cfg(all(feature = "time", not(feature = "chrono")))]
type Date = time::Date;

#[cfg(all(feature = "jiff", not(any(feature = "chrono", feature = "time"))))]
type Date = jiff::civil::Date;

#[cfg(not(any(feature = "chrono", feature = "time", feature = "jiff")))]
type Date = compact_str::CompactString;

#[derive(Clone, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "PascalCase"))]
pub struct InstallerManifest {
    /// The unique identifier for a given package.
    ///
    /// This value is generally in the form of `Publisher.Package`. It is case-sensitive, and this
    /// value must match the folder structure under the partition directory in GitHub.
    pub package_identifier: PackageIdentifier,

    /// The version of the package.
    ///
    /// It is related to the specific release this manifests targets. In some cases you will see a
    /// perfectly formed [semantic version] number, and in other cases you might see something
    /// different. These may be date driven, or they might have other characters with some package
    /// specific meaning for example.
    ///
    /// The Windows Package Manager client uses this version to determine if an upgrade for a
    /// package is available. In some cases, packages may be released with a marketing driven
    /// version, and that causes trouble with the [`winget upgrade`] command.
    ///
    /// The current best practice is to use the value reported in Add / Remove Programs when this
    /// version of the package is installed. In some cases, packages do not report a version
    /// resulting in an upgrade loop or other unwanted behavior.
    ///
    /// [semantic version]: https://semver.org/
    /// [`winget upgrade`]: https://docs.microsoft.com/windows/package-manager/winget/upgrade
    pub package_version: PackageVersion,

    /// The distribution channel for a package.
    ///
    /// Examples may include "stable" or "beta".
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub channel: Option<Channel>,

    /// The locale for an installer not the package meta-data.
    ///
    /// Some installers are compiled with locale or language specific properties. If this key is
    /// present, it is used to represent the package locale for an installer.
    #[cfg_attr(
        feature = "serde",
        serde(rename = "InstallerLocale", skip_serializing_if = "Option::is_none")
    )]
    pub locale: Option<LanguageTag>,

    /// The Windows platform targeted by the installer.
    ///
    /// The Windows Package Manager currently supports "Windows.Desktop" and "Windows.Universal".
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Platform::is_empty", default)
    )]
    pub platform: Platform,

    /// The minimum version of the Windows operating system supported by the package.
    #[cfg_attr(
        feature = "serde",
        serde(rename = "MinimumOSVersion", skip_serializing_if = "Option::is_none")
    )]
    pub minimum_os_version: Option<MinimumOSVersion>,

    /// The installer type for the package.
    ///
    /// The Windows Package Manager supports [MSIX], [MSI], and executable installers. Some well
    /// known formats ([Inno], [Nullsoft], [WiX], and [Burn]) provide standard sets of installer
    /// switches to provide different installer experiences. Portable packages are supported as of
    /// Windows Package Manager 1.3. Zip packages are supported as of Windows Package Manager 1.5.
    ///
    /// [MSIX]: https://docs.microsoft.com/windows/msix/overview
    /// [MSI]: https://docs.microsoft.com/windows/win32/msi/windows-installer-portal
    /// [Inno]: https://jrsoftware.org/isinfo.php
    /// [Nullsoft]: https://sourceforge.net/projects/nsis
    /// [WiX]: https://wixtoolset.org/
    /// [Burn]: https://wixtoolset.org/docs/v3/bundle/
    #[cfg_attr(
        feature = "serde",
        serde(rename = "InstallerType", skip_serializing_if = "Option::is_none")
    )]
    pub r#type: Option<InstallerType>,

    /// The installer type of the file within the archive which will be used as the installer.
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub nested_installer_type: Option<NestedInstallerType>,

    /// A list of all the installers to be executed within an archive.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "BTreeSet::is_empty", default)
    )]
    pub nested_installer_files: BTreeSet<NestedInstallerFiles>,

    /// The scope the package is installed under.
    ///
    /// The two configurations are [`user`] and [`machine`]. Some installers support only one of
    /// these scopes while others support both via arguments passed to the installer using
    /// [`InstallerSwitches`].
    ///
    /// [`user`]: Scope::User
    /// [`machine`]: Scope::Machine
    /// [`InstallerSwitches`]: InstallerSwitches
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub scope: Option<Scope>,

    /// The install modes supported by the installer.
    ///
    /// The Microsoft community package repository requires a package support "silent" and
    /// "silent with progress". The Windows Package Manager also supports "interactive" installers.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "InstallModes::is_empty", default)
    )]
    pub install_modes: InstallModes,

    /// The set of switches passed to installers.
    #[cfg_attr(
        feature = "serde",
        serde(
            rename = "InstallerSwitches",
            skip_serializing_if = "InstallerSwitches::is_empty",
            default
        )
    )]
    pub switches: InstallerSwitches,

    /// Any status codes returned by the installer representing a success condition other than zero.
    #[cfg_attr(
        feature = "serde",
        serde(
            rename = "InstallerSuccessCodes",
            skip_serializing_if = "BTreeSet::is_empty",
            default
        )
    )]
    pub success_codes: BTreeSet<InstallerSuccessCode>,

    /// Any status codes returned by the installer representing a condition other than zero.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "BTreeSet::is_empty", default)
    )]
    pub expected_return_codes: BTreeSet<ExpectedReturnCodes>,

    /// What the Windows Package Manager should do regarding the currently installed package during
    /// a package upgrade.
    ///
    /// If the package should be uninstalled first, the [`uninstallPrevious`] value should be
    /// specified. If the package should not be upgraded through `WinGet`, the [`deny`] value should
    /// be specified.
    ///
    /// [`uninstallPrevious`]: UpgradeBehavior::UninstallPrevious
    /// [`deny`]: UpgradeBehavior::Deny
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub upgrade_behavior: Option<UpgradeBehavior>,

    /// Any commands or aliases used to execute the package after it has been installed.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "BTreeSet::is_empty", default)
    )]
    pub commands: BTreeSet<Command>,

    /// Any protocols (i.e. URI schemes) supported by the package. For example: `["ftp", "ldap"]`.
    /// Entries shouldn't have trailing colons. The Windows Package Manager does not support any
    /// behavior related to protocols handled by a package.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "BTreeSet::is_empty", default)
    )]
    pub protocols: BTreeSet<Protocol>,

    /// Any file extensions supported by the package.
    ///
    /// For example: `["html", "jpg"]`. Entries shouldn't have leading dots. The Windows Package
    /// Manager does not support any behavior related to the file extensions supported by the
    /// package.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "BTreeSet::is_empty", default)
    )]
    pub file_extensions: BTreeSet<FileExtension>,

    /// Any dependencies required to install or run the package.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Dependencies::is_empty", default)
    )]
    pub dependencies: Dependencies,

    /// The [package family name] specified in an MSIX installer.
    ///
    /// This value is used to assist with matching packages from a source to the program installed
    /// in Windows via Add / Remove Programs for list, and upgrade behavior.
    ///
    /// [package family name]: https://learn.microsoft.com/windows/apps/desktop/modernize/package-identity-overview#package-family-name
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub package_family_name: Option<PackageFamilyName<'static>>,

    /// The [product code].
    ///
    /// This value is used to assist with matching packages from a source to the program installed
    /// in Windows via Add / Remove Programs for list, and upgrade behavior.
    ///
    /// [product code]: https://learn.microsoft.com/windows/win32/msi/product-codes
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub product_code: Option<String>,

    /// The capabilities provided by an MSIX package.
    ///
    /// More information is available for [App capability declarations].
    ///
    /// [App capability declarations]: https://docs.microsoft.com/windows/uwp/packaging/app-capability-declarations
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "BTreeSet::is_empty", default)
    )]
    pub capabilities: BTreeSet<Capability>,

    /// The restricted capabilities provided by an MSIX package.
    ///
    /// More information is available for [App capability declarations].
    ///
    /// [App capability declarations]: https://docs.microsoft.com/windows/uwp/packaging/app-capability-declarations
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "BTreeSet::is_empty", default)
    )]
    pub restricted_capabilities: BTreeSet<RestrictedCapability>,

    /// Any markets a package may or may not be installed in.
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub markets: Option<Markets>,

    /// The behavior associated with installers that abort the terminal.
    ///
    /// This most often occurs when a user is performing an upgrade of the running terminal.
    #[cfg_attr(
        feature = "serde",
        serde(
            rename = "InstallerAbortsTerminal",
            skip_serializing_if = "core::ops::Not::not",
            default
        )
    )]
    pub aborts_terminal: bool,

    /// The release date for a package, in RFC 3339 / ISO 8601 format, i.e. "YYYY-MM-DD".
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub release_date: Option<Date>,

    /// The requirement to have an install location specified.
    ///
    /// These installers are known to deploy files to the location the installer is executed in.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "core::ops::Not::not", default)
    )]
    pub install_location_required: bool,

    /// Identifies packages that upgrade themselves.
    ///
    /// By default, they are excluded from `winget upgrade --all`.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "core::ops::Not::not", default)
    )]
    pub require_explicit_upgrade: bool,

    /// Whether a warning message is displayed to the user prior to install or upgrade if the
    /// package is known to interfere with any running applications.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "core::ops::Not::not", default)
    )]
    pub display_install_warnings: bool,

    /// Any architectures a package is known not to be compatible with.
    ///
    /// Generally, this is associated with emulation modes.
    #[cfg_attr(
        feature = "serde",
        serde(
            rename = "UnsupportedOSArchitectures",
            skip_serializing_if = "UnsupportedOSArchitecture::is_empty",
            default
        )
    )]
    pub unsupported_os_architectures: UnsupportedOSArchitecture,

    /// The list of Windows Package Manager Client arguments the installer does not support.
    ///
    /// Only the `--log` and `--location` arguments can be specified as unsupported arguments for an
    /// installer.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "UnsupportedArguments::is_empty", default)
    )]
    pub unsupported_arguments: UnsupportedArguments,

    /// The values reported by Windows Apps & Features.
    ///
    /// When a package is installed, entries are made into the Windows Registry.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "AppsAndFeaturesEntries::is_empty", default)
    )]
    pub apps_and_features_entries: AppsAndFeaturesEntries,

    /// The scope in which scope a package is required to be executed under.
    ///
    /// Some packages require user level execution while others require administrative level
    /// execution.
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub elevation_requirement: Option<ElevationRequirement>,

    /// Allows for additional metadata to be used for deeper installation detection.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "InstallationMetadata::is_empty", default)
    )]
    pub installation_metadata: InstallationMetadata,

    /// When true, this flag will prohibit the manifest from being downloaded for offline
    /// installation with the winget download command.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "core::ops::Not::not", default)
    )]
    pub download_command_prohibited: bool,

    /// This field controls what method is used to repair existing installations of packages.
    ///
    /// Specifying `modify` will use the `ModifyPath` string from the package's ARP data,
    /// `uninstaller` will use the Uninstall string from the package's ARP data, and `installer`
    /// will download and run the installer. In each case, the `Repair` value from
    /// `InstallerSwitches` will be added as an argument when invoking the command to repair the
    /// package.
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub repair_behavior: Option<RepairBehavior>,

    /// This field controls the behavior of environment variables when installing portable packages
    /// from an archive (i.e. `zip`).
    ///
    /// Specifying `true` will add the install location directly to the `PATH` environment variable.
    /// Specifying `false` will use the default behavior of adding a symlink to the `links` folder,
    /// if supported, or adding the install location directly to `PATH` if symlinks are not
    /// supported.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "core::ops::Not::not", default)
    )]
    pub archive_binaries_depend_on_path: bool,

    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub authentication: Option<Authentication>,

    pub installers: Vec<Installer>,

    /// The manifest type.
    ///
    /// Must have the value [`installer`]. The Microsoft community package repository validation
    /// pipelines also use this value to determine appropriate validation rules when evaluating this
    /// file.
    ///
    /// [`installer`]: ManifestType::Installer
    #[cfg_attr(feature = "serde", serde(default = "ManifestType::installer"))]
    pub manifest_type: ManifestType,

    /// The manifest syntax version.
    ///
    /// Must have the value `1.12.0`. The Microsoft community package repository validation
    /// pipelines also use this value to determine appropriate validation rules when evaluating this
    /// file.
    #[cfg_attr(feature = "serde", serde(default))]
    pub manifest_version: ManifestVersion,
}

impl Manifest for InstallerManifest {
    const SCHEMA: &'static str = "https://aka.ms/winget-manifest.installer.1.12.0.schema.json";
    const TYPE: ManifestType = ManifestType::Installer;
}

impl InstallerManifest {
    #[expect(
        clippy::cognitive_complexity,
        reason = "The resulting complexity is generated by a macro"
    )]
    pub fn optimize(&mut self) {
        macro_rules! optimize_keys {
            ($($($field:ident).+),* $(,)?) => {
                $(
                    if let Ok(nested) = self
                        .installers
                        .iter_mut()
                        .map(|installer| &mut installer.$($field).+)
                        .all_equal_value()
                    {
                        if <_ as PartialEq>::ne(nested, &Default::default()) {
                            self.$($field).+ = core::mem::take(nested);
                            for installer in &mut self.installers {
                                installer.$($field).+ = Default::default();
                            }
                        }
                    } else {
                        self.$($field).+ = Default::default();
                    }
                )*
            };
        }

        optimize_keys!(
            locale,
            platform,
            minimum_os_version,
            r#type,
            nested_installer_type,
            nested_installer_files,
            scope,
            install_modes,
            switches.silent,
            switches.silent_with_progress,
            switches.interactive,
            switches.install_location,
            switches.log,
            switches.upgrade,
            switches.custom,
            switches.repair,
            success_codes,
            expected_return_codes,
            upgrade_behavior,
            commands,
            protocols,
            file_extensions,
            dependencies.windows_features,
            dependencies.windows_libraries,
            dependencies.package,
            dependencies.external,
            package_family_name,
            product_code,
            capabilities,
            restricted_capabilities,
            markets,
            aborts_terminal,
            release_date,
            install_location_required,
            require_explicit_upgrade,
            display_install_warnings,
            unsupported_os_architectures,
            unsupported_arguments,
            apps_and_features_entries,
            elevation_requirement,
            installation_metadata,
            download_command_prohibited,
            repair_behavior,
            archive_binaries_depend_on_path,
        );

        self.manifest_version = ManifestVersion::default();

        self.installers.sort_unstable();
        self.installers.dedup();
    }
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Hash, Ord, PartialOrd)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "PascalCase"))]
pub struct Installer {
    /// The locale for an installer *not* the package meta-data.
    ///
    /// Some installers are compiled with locale or language specific properties. If this key is
    /// present, it is used to represent the package locale for an installer.
    #[cfg_attr(
        feature = "serde",
        serde(rename = "InstallerLocale", skip_serializing_if = "Option::is_none")
    )]
    pub locale: Option<LanguageTag>,

    /// The Windows platform targeted by the installer.
    ///
    /// The Windows Package Manager currently supports "Windows.Desktop" and "Windows.Universal".
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Platform::is_empty", default)
    )]
    pub platform: Platform,

    /// The minimum version of the Windows operating system supported by the package.
    #[cfg_attr(
        feature = "serde",
        serde(rename = "MinimumOSVersion", skip_serializing_if = "Option::is_none")
    )]
    pub minimum_os_version: Option<MinimumOSVersion>,

    /// The hardware architecture targeted by the installer.
    ///
    /// The Windows Package Manager will attempt to determine the best architecture to use. If
    /// emulation is available and the native hardware architecture does not have a supported
    /// installer, the emulated architecture may be used.
    pub architecture: Architecture,

    /// The installer type for the package.
    ///
    /// The Windows Package Manager supports [MSIX], [MSI], and executable installers. Some well
    /// known formats ([Inno], [Nullsoft], [WiX], and [Burn]) provide standard sets of installer
    /// switches to provide different installer experiences. Portable packages are supported as of
    /// Windows Package Manager 1.3. Zip packages are supported as of Windows Package Manager 1.5.
    ///
    /// [MSIX]: https://docs.microsoft.com/windows/msix/overview
    /// [MSI]: https://docs.microsoft.com/windows/win32/msi/windows-installer-portal
    /// [Inno]: https://jrsoftware.org/isinfo.php
    /// [Nullsoft]: https://sourceforge.net/projects/nsis
    /// [WiX]: https://wixtoolset.org/
    /// [Burn]: https://wixtoolset.org/docs/v3/bundle/
    #[cfg_attr(
        feature = "serde",
        serde(rename = "InstallerType", skip_serializing_if = "Option::is_none")
    )]
    pub r#type: Option<InstallerType>,

    /// The installer type of the file within the archive which will be used as the installer.
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub nested_installer_type: Option<NestedInstallerType>,

    /// A list of all the installers to be executed within an archive.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "BTreeSet::is_empty", default)
    )]
    pub nested_installer_files: BTreeSet<NestedInstallerFiles>,

    /// The scope the package is installed under.
    ///
    /// The two configurations are [`user`] and [`machine`]. Some installers support only one of
    /// these scopes while others support both via arguments passed to the installer using
    /// [`InstallerSwitches`].
    ///
    /// [`user`]: Scope::User
    /// [`machine`]: Scope::Machine
    /// [`InstallerSwitches`]: InstallerSwitches
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub scope: Option<Scope>,

    /// The URL to download the installer.
    #[cfg_attr(feature = "serde", serde(rename = "InstallerUrl"))]
    pub url: DecodedUrl,

    /// The SHA 256 hash for the installer. It is used to confirm the installer has not been
    /// modified. The Windows Package Manager will compare the hash in the manifest with the
    /// calculated hash of the installer after it has been downloaded.
    #[cfg_attr(feature = "serde", serde(rename = "InstallerSha256"))]
    pub sha_256: Sha256String,

    /// The signature file (AppxSignature.p7x) inside an MSIX installer. It is used to provide
    /// streaming install for MSIX packages.
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub signature_sha_256: Option<Sha256String>,

    /// The install modes supported by the installer.
    ///
    /// The Microsoft community package repository requires a package support "silent" and
    /// "silent with progress". The Windows Package Manager also supports "interactive" installers.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "InstallModes::is_empty", default)
    )]
    pub install_modes: InstallModes,

    /// The set of switches passed to installers.
    #[cfg_attr(
        feature = "serde",
        serde(
            rename = "InstallerSwitches",
            skip_serializing_if = "InstallerSwitches::is_empty",
            default
        )
    )]
    pub switches: InstallerSwitches,

    /// Any status codes returned by the installer representing a success condition other than zero.
    #[cfg_attr(
        feature = "serde",
        serde(
            rename = "InstallerSuccessCodes",
            skip_serializing_if = "BTreeSet::is_empty",
            default
        )
    )]
    pub success_codes: BTreeSet<InstallerSuccessCode>,

    /// Any status codes returned by the installer representing a condition other than zero.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "BTreeSet::is_empty", default)
    )]
    pub expected_return_codes: BTreeSet<ExpectedReturnCodes>,

    /// What the Windows Package Manager should do regarding the currently installed package during
    /// a package upgrade.
    ///
    /// If the package should be uninstalled first, the [`uninstallPrevious`] value should be
    /// specified. If the package should not be upgraded through `WinGet`, the [`deny`] value should
    /// be specified.
    ///
    /// [`uninstallPrevious`]: UpgradeBehavior::UninstallPrevious
    /// [`deny`]: UpgradeBehavior::Deny
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub upgrade_behavior: Option<UpgradeBehavior>,

    /// Any commands or aliases used to execute the package after it has been installed.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "BTreeSet::is_empty", default)
    )]
    pub commands: BTreeSet<Command>,

    /// Any protocols (i.e. URI schemes) supported by the package. For example: `["ftp", "ldap"]`.
    /// Entries shouldn't have trailing colons. The Windows Package Manager does not support any
    /// behavior related to protocols handled by a package.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "BTreeSet::is_empty", default)
    )]
    pub protocols: BTreeSet<Protocol>,

    /// Any file extensions supported by the package.
    ///
    /// For example: `["html", "jpg"]`. Entries shouldn't have leading dots. The Windows Package
    /// Manager does not support any behavior related to the file extensions supported by the
    /// package.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "BTreeSet::is_empty", default)
    )]
    pub file_extensions: BTreeSet<FileExtension>,

    /// Any dependencies required to install or run the package.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Dependencies::is_empty", default)
    )]
    pub dependencies: Dependencies,

    /// The [package family name] specified in an MSIX installer.
    ///
    /// This value is used to assist with matching packages from a source to the program installed
    /// in Windows via Add / Remove Programs for list, and upgrade behavior.
    ///
    /// [package family name]: https://learn.microsoft.com/windows/apps/desktop/modernize/package-identity-overview#package-family-name
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub package_family_name: Option<PackageFamilyName<'static>>,

    /// The [product code].
    ///
    /// This value is used to assist with matching packages from a source to the program installed
    /// in Windows via Add / Remove Programs for list, and upgrade behavior.
    ///
    /// [product code]: https://learn.microsoft.com/windows/win32/msi/product-codes
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub product_code: Option<String>,

    /// The capabilities provided by an MSIX package.
    ///
    /// More information is available for [App capability declarations].
    ///
    /// [App capability declarations]: https://docs.microsoft.com/windows/uwp/packaging/app-capability-declarations
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "BTreeSet::is_empty", default)
    )]
    pub capabilities: BTreeSet<Capability>,

    /// The restricted capabilities provided by an MSIX package.
    ///
    /// More information is available for [App capability declarations].
    ///
    /// [App capability declarations]: https://docs.microsoft.com/windows/uwp/packaging/app-capability-declarations
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "BTreeSet::is_empty", default)
    )]
    pub restricted_capabilities: BTreeSet<RestrictedCapability>,

    /// Any markets a package may or may not be installed in.
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub markets: Option<Markets>,

    /// The behavior associated with installers that abort the terminal.
    ///
    /// This most often occurs when a user is performing an upgrade of the running terminal.
    #[cfg_attr(
        feature = "serde",
        serde(
            rename = "InstallerAbortsTerminal",
            skip_serializing_if = "core::ops::Not::not",
            default
        )
    )]
    pub aborts_terminal: bool,

    /// The release date for a package, in RFC 3339 / ISO 8601 format, i.e. "YYYY-MM-DD".
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub release_date: Option<Date>,

    /// The requirement to have an install location specified.
    ///
    /// These installers are known to deploy files to the location the installer is executed in.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "core::ops::Not::not", default)
    )]
    pub install_location_required: bool,

    /// Identifies packages that upgrade themselves.
    ///
    /// By default, they are excluded from `winget upgrade --all`.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "core::ops::Not::not", default)
    )]
    pub require_explicit_upgrade: bool,

    /// Whether a warning message is displayed to the user prior to install or upgrade if the
    /// package is known to interfere with any running applications.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "core::ops::Not::not", default)
    )]
    pub display_install_warnings: bool,

    /// Any architectures a package is known not to be compatible with.
    ///
    /// Generally, this is associated with emulation modes.
    #[cfg_attr(
        feature = "serde",
        serde(
            rename = "UnsupportedOSArchitectures",
            skip_serializing_if = "UnsupportedOSArchitecture::is_empty",
            default
        )
    )]
    pub unsupported_os_architectures: UnsupportedOSArchitecture,

    /// The list of Windows Package Manager Client arguments the installer does not support.
    ///
    /// Only the `--log` and `--location` arguments can be specified as unsupported arguments for an
    /// installer.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "UnsupportedArguments::is_empty", default)
    )]
    pub unsupported_arguments: UnsupportedArguments,

    /// The values reported by Windows Apps & Features.
    ///
    /// When a package is installed, entries are made into the Windows Registry.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "AppsAndFeaturesEntries::is_empty", default)
    )]
    pub apps_and_features_entries: AppsAndFeaturesEntries,

    /// The scope in which scope a package is required to be executed under.
    ///
    /// Some packages require user level execution while others require administrative level
    /// execution.
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub elevation_requirement: Option<ElevationRequirement>,

    /// Allows for additional metadata to be used for deeper installation detection.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "InstallationMetadata::is_empty", default)
    )]
    pub installation_metadata: InstallationMetadata,

    /// When true, this flag will prohibit the manifest from being downloaded for offline
    /// installation with the winget download command.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "core::ops::Not::not", default)
    )]
    pub download_command_prohibited: bool,

    /// This field controls what method is used to repair existing installations of packages.
    ///
    /// Specifying `modify` will use the `ModifyPath` string from the package's ARP data,
    /// `uninstaller` will use the Uninstall string from the package's ARP data, and `installer`
    /// will download and run the installer. In each case, the `Repair` value from
    /// `InstallerSwitches` will be added as an argument when invoking the command to repair the
    /// package.
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub repair_behavior: Option<RepairBehavior>,

    /// This field controls the behavior of environment variables when installing portable packages
    /// from an archive (i.e. `zip`).
    ///
    /// Specifying `true` will add the install location directly to the `PATH` environment variable.
    /// Specifying `false` will use the default behavior of adding a symlink to the `links` folder,
    /// if supported, or adding the install location directly to `PATH` if symlinks are not
    /// supported.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "core::ops::Not::not", default)
    )]
    pub archive_binaries_depend_on_path: bool,

    /// This field controls the authentication for Entra ID secured private sources.
    ///
    /// Resource and scope information can be included if a specific resource is needed to download
    /// or install the package.
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub authentication: Option<Authentication>,
}

impl Installer {
    /// Merges two installers.
    ///
    /// If a key of `self` is equal to its default, it will take the value from `other`. If the key
    /// of `self` is not equal to its default, it will retain that value and the equivalent key in
    /// `other` is ignored.
    #[expect(
        clippy::cognitive_complexity,
        reason = "The resulting complexity is generated by a macro"
    )]
    #[must_use]
    pub fn merge_with(mut self, other: Self) -> Self {
        macro_rules! merge_keys {
            (
                $($($field:ident).+),*,
                [$($switch:ident),* $(,)?]$(,)?
            ) => {
                #[inline]
                fn default<T: Default>(_: &T) -> T {
                    T::default()
                }

                $(
                    if self.$($field).+ == default(&self.$($field).+) {
                        self.$($field).+ = other.$($field).+;
                    }
                )*

                $(
                    match (&mut self.switches.$switch, &other.switches.$switch) {
                        (None, Some(other_switch)) => {
                            self.switches.$switch = Some(other_switch.clone());
                        },
                        (Some(self_switch), Some(other_switch)) => {
                            for part in other_switch {
                                if !self_switch.contains(part) {
                                    self_switch.push(part.clone());
                                }
                            }
                        },
                        _ => {}
                    }
                )*
            };
        }

        merge_keys!(
            locale,
            platform,
            minimum_os_version,
            r#type,
            nested_installer_type,
            nested_installer_files,
            scope,
            install_modes,
            success_codes,
            expected_return_codes,
            upgrade_behavior,
            commands,
            protocols,
            file_extensions,
            dependencies,
            package_family_name,
            product_code,
            capabilities,
            restricted_capabilities,
            markets,
            aborts_terminal,
            release_date,
            install_location_required,
            require_explicit_upgrade,
            display_install_warnings,
            unsupported_os_architectures,
            unsupported_arguments,
            apps_and_features_entries,
            elevation_requirement,
            installation_metadata,
            download_command_prohibited,
            repair_behavior,
            archive_binaries_depend_on_path,
            [
                silent,
                silent_with_progress,
                interactive,
                install_location,
                log,
                upgrade,
                custom,
                repair
            ],
        );

        self
    }
}

#[cfg(test)]
mod tests {
    use alloc::vec;

    use crate::{
        installer::{Architecture, Installer, InstallerManifest, InstallerSwitches},
        shared::LanguageTag,
    };

    #[test]
    fn optimize_duplicate_locale() {
        let mut manifest = InstallerManifest {
            installers: vec![
                Installer {
                    locale: Some("en-US".parse::<LanguageTag>().unwrap()),
                    architecture: Architecture::X86,
                    ..Installer::default()
                },
                Installer {
                    locale: Some("en-US".parse::<LanguageTag>().unwrap()),
                    architecture: Architecture::X64,
                    ..Installer::default()
                },
            ],
            ..InstallerManifest::default()
        };

        manifest.optimize();

        assert_eq!(
            manifest,
            InstallerManifest {
                locale: Some("en-US".parse::<LanguageTag>().unwrap()),
                installers: vec![
                    Installer {
                        architecture: Architecture::X86,
                        ..Installer::default()
                    },
                    Installer {
                        architecture: Architecture::X64,
                        ..Installer::default()
                    },
                ],
                ..InstallerManifest::default()
            }
        )
    }

    #[test]
    fn optimize_duplicate_switch() {
        let mut manifest = InstallerManifest {
            installers: vec![
                Installer {
                    architecture: Architecture::X86,
                    switches: InstallerSwitches::builder()
                        .maybe_silent("--silent".parse().ok())
                        .maybe_custom("--custom".parse().ok())
                        .build(),
                    ..Installer::default()
                },
                Installer {
                    architecture: Architecture::X64,
                    switches: InstallerSwitches::builder()
                        .maybe_silent("--silent".parse().ok())
                        .build(),
                    ..Installer::default()
                },
            ],
            ..InstallerManifest::default()
        };

        manifest.optimize();

        assert_eq!(
            manifest,
            InstallerManifest {
                switches: InstallerSwitches::builder()
                    .maybe_silent("--silent".parse().ok())
                    .build(),
                installers: vec![
                    Installer {
                        architecture: Architecture::X86,
                        switches: InstallerSwitches::builder()
                            .maybe_custom("--custom".parse().ok())
                            .build(),
                        ..Installer::default()
                    },
                    Installer {
                        architecture: Architecture::X64,
                        ..Installer::default()
                    },
                ],
                ..InstallerManifest::default()
            }
        )
    }
}