chr
2026-04-05 fe750b791d5b517cc4e9bc8e99a9a75139a0cfba
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
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
//            Copyright Keysight Technologies 2012-2019
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, you can obtain one at http://mozilla.org/MPL/2.0/.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.IO.Compression;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Security.Cryptography;
 
namespace OpenTap.Package
{
    /// <summary>
    /// Represents a plugin (type that derives from ITapPlugin) in a payload file of an OpenTAP package.
    /// </summary>
    [XmlType("Plugin")]
    public class PluginFile
    {
        /// <summary>
        /// The namespace qualified name of the type.
        /// </summary>
        [XmlAttribute]
        public string Type { get; set; }
        
        /// <summary>
        /// The display name of the plugin base type that Type derives from. E.g. TestStep.
        /// </summary>
        [XmlAttribute]
        public string BaseType { get; set; }
        /// <summary> The display name of the plugin type as specified by its <see cref="DisplayAttribute"/>.</summary>
        public string Name { get; set; }
        /// <summary> Obsolete. Always null. Use Groups instead. </summary>
        [XmlIgnore]
        [Obsolete]
        public string Group { get; set; }
        /// <summary> The display order of the plugin type as specified by its <see cref="DisplayAttribute"/>.</summary>
        public double Order { get; set; }
        /// <summary> The browsable state of the plugin type as specified by a System.ComponentModel.BrowsableAttribute.</summary>
        public bool Browsable { get; set; }
        /// <summary> The description of the plugin type as specified by its <see cref="DisplayAttribute"/>.</summary>
        public string Description { get; set; }
        /// <summary> The collapsed state of the display group to which the plugin belongs as specified by its <see cref="DisplayAttribute"/>.</summary>
        public bool Collapsed { get; set; }
        /// <summary> The array of display groups of the plugin type as specified by its <see cref="DisplayAttribute"/>.</summary>
        public string[] Groups { get; set; }
        
        /// <summary>
        /// The hardware models supported by this plugin. Specified by <see cref="SupportedModelsAttribute"/>
        /// </summary>
        public SupportedModelsAttribute[] SupportedModels { get; set; }
 
        /// <summary>
        /// Creates a new PluginFile.
        /// </summary>
        public PluginFile()
        {
            Browsable = true;
        }
 
        /// <summary>
        /// Obsolete. Use !Browsable instead.
        /// </summary>
        [Obsolete]
        public bool ShouldSerializeBrowsable()
        {
            return !Browsable;
        }
    }
 
    /// <summary>
    /// Information about a file in a package. 
    /// </summary>
    [XmlType("File")]
    [DebuggerDisplay("{FileName} ({RelativeDestinationPath})")]
    public class PackageFile
    {
        /// <summary>
        /// The location of this file.
        /// </summary>
        [XmlIgnore]
        public string FileName
        {
            set => sourcePath = value;
            // When this type is deserialized from an xml file, FileName will 
            // be unset, so we use the value from RelativeDestinationPath
            get => sourcePath ??  RelativeDestinationPath;
        }
 
    
        string sourcePath;
 
        /// <summary> Source of the file. Can be different from RelativeDestinationPath. </summary>
        [XmlAttribute("SourcePath")]
        [DefaultValue(null)]
        [XmlIgnore]
        public string SourcePath
        {
            get => sourcePath;
            set => sourcePath = value;
        }
 
        /// <summary>
        /// Relative location of file ( to OpenTAP folder).
        /// </summary>
        [XmlAttribute("Path")]
        public string RelativeDestinationPath { get; set; }
 
        /// <summary>
        /// The contained plugin types.
        /// </summary>
        [DefaultValue(null)]
        public List<PluginFile> Plugins { get; set; }
 
        /// <summary>
        /// Dependencies to ignore. This should contain a list of assembly names.
        /// </summary>
        [XmlElement(ElementName = "IgnoreDependency")]
        public List<string> IgnoredDependencies { get; set; }
 
        /// <summary>
        /// Custom data meant for consumption by <see cref="ICustomPackageAction"/> plugins.
        /// </summary>
        public List<ICustomPackageData> CustomData { get; set; }
 
        /// <summary>
        /// Dependent assemblies.
        /// </summary>
        [XmlIgnore]
        internal List<AssemblyData> DependentAssemblies { get; set; }
        
        /// <summary> Other type data dependency sources (e.g Python type data) </summary>
        [XmlIgnore]
        internal List<ITypeDataSource> DependentTypeDataSources { get; set; }
 
        internal IEnumerable<ITypeDataSource> AllDependencies => DependentAssemblies.Concat(DependentTypeDataSources);
 
        /// <summary>
        /// License required by the plugin file.
        /// </summary>
        [XmlAttribute("LicenseRequired")]
        [DefaultValue("")]
        public string LicenseRequired { get; set; } = "";
 
        /// <summary>
        /// Creates a new instance of PackageFile.
        /// </summary>
        public PackageFile()
        {
            DependentAssemblies = new List<AssemblyData>();
            DependentTypeDataSources = new List<ITypeDataSource>();
            Plugins = new List<PluginFile>();
            IgnoredDependencies = new List<string>();
            CustomData = new List<ICustomPackageData>();
        }
    }
 
    /// <summary>
    /// Represents a dependency on a package.
    /// </summary>
    [DebuggerDisplay("{Name} ({Version})")]
    public class PackageDependency
    {
        /// <summary>
        /// Name of the package to which this dependency reffers.
        /// </summary>
        public string Name { get; private set; }
 
        /// <summary>
        /// Specifying requirements to the version of the package. Never null.
        /// </summary>
        public VersionSpecifier Version { get; set; }
 
        /// <summary>
        /// Returns raw version string.
        /// </summary>
        /// <returns>Raw version string from input. Null if the raw input is not set</returns>
        internal string RawVersion
        {
            get;
            private set;
        }
 
        /// <summary>
        /// This constructor is only used for serialization.
        /// </summary>
        public PackageDependency(string name, VersionSpecifier version, string rawVersion = null)
        {
            if(version == null)
                throw new ArgumentNullException("version");
            Name = name;
            Version = version;
            RawVersion = rawVersion;
        }
 
        /// <summary>
        /// Compares this PackageDependency to another object.
        /// </summary>
        public override bool Equals(object obj)
        {
            if (obj is PackageDependency dep)
                return Equals(dep.Name, Name) && Equals(dep.Version, Version);
            return false;
        }
 
        /// <summary>
        /// Returns the hash code for this PackageDependency.
        /// </summary>
        public override int GetHashCode() =>  (Name ?? "").GetHashCode() * 7489019 + (RawVersion ?? "").GetHashCode() * 41077013;
    }
 
    /// <summary>
    /// Represents an action/step that can be executed during or after installation of a package.
    /// </summary>
    public class ActionStep
    {
        /// <summary>
        /// Path to an exe file to execute as part of this step.
        /// </summary>
        /// <value></value>
        [XmlAttribute("ExeFile")]
        public string ExeFile { get; set; }
 
        /// <summary>
        /// A comma separated list of expected exit code integers. Default is "0".
        /// </summary>
        [XmlAttribute(nameof(ExpectedExitCodes))]
        public string ExpectedExitCodes { get; set; } = "0";
 
        /// <summary>
        /// False; Action stdout and stderr will be forwarded
        /// True; Action stdout and stderr will be suppressed
        /// </summary>
        [XmlAttribute("Quiet")]
        public bool Quiet { get; set; } = false;
 
        /// <summary>
        /// False; package installation should fail if the executable does not exist.
        /// True; package installation should continue if the executable does not exist.
        /// </summary>
        [XmlAttribute("Optional")]
        public bool Optional { get; set; } = false;
 
        /// <summary>
        /// Arguments to the exe file.
        /// </summary>
        [XmlAttribute("Arguments")]
        public string Arguments { get; set; }
 
        /// <summary>
        /// Name of the action in which this step should be executed. E.g. "install".
        /// </summary>
        /// <value></value>
        [XmlAttribute("ActionName")]
        public string ActionName { get; set; }
 
        /// <summary>
        /// Indicates whether to use the operating system shell to start the process.
        /// </summary>
        [XmlAttribute("UseShellExecute")]
        [DefaultValue(false)]
        public bool UseShellExecute { get; set; }
 
        /// <summary>
        /// Indicates whether to start the process in a new window.
        /// </summary>
        /// <value></value>
        [XmlAttribute("CreateNoWindow")]
        [DefaultValue(false)]
        public bool CreateNoWindow { get; set; }
 
        /// <summary>
        /// Creates a new ActionStep with default values.
        /// </summary>
        public ActionStep()
        {
            UseShellExecute = false;
            CreateNoWindow = false;
        }
    }
 
    /// <summary>
    /// CPU architectures that a package can support.
    /// </summary>
    public enum CpuArchitecture
    {
        /// <summary> Unspecified processor architecture.</summary>
        Unspecified,
        /// <summary> Any processor architecture. </summary>
        AnyCPU,
        /// <summary> An Intel-based 32-bit processor architecture. </summary>
        x86,
        /// <summary> An Intel-based 64-bit processor architecture. </summary>
        x64,
        /// <summary> A 32-bit ARM processor architecture. </summary>
        arm,
        /// <summary> A 64-bit ARM processor architecture. </summary>
        arm64
    }
 
    [Display("Please review the End User License Agreement")]
    class EulaAcceptanceDialog
    {
        public enum Acceptance
        {
            [Display("I accept the agreement")]
            Accept,
            [Display("I do not accept the agreement")]
            Decline,
        }
        private readonly EULA _eula;
        private PackageDef _packageDef;
        private static readonly TraceSource log = Log.CreateSource("EULA");
        
        [Browsable(true)]
        [Layout(LayoutMode.FullRow | LayoutMode.WrapText)]
        [Display("Message", Order: 1)]
        public string Message => $"Please review the end user license agreement at {_eula.Source}";
 
        [Browsable(true)]
        [Layout(LayoutMode.FullRow)]
        [Display("View License Agreement", Order: 2)]
        public void OpenEula()
        {
            if (!Uri.TryCreate(_eula.Source, UriKind.RelativeOrAbsolute, out var uri))
            {
                log.Error($"Cannot determine resource type '{_eula.Source}'. Please review it manually, if possible.");
                return;
            }
 
            string path = null;
            if (uri.IsAbsoluteUri && !uri.IsFile)
            {
                // Assume some Uri scheme which can be opened (most likely http)
                path = uri.AbsoluteUri;
            }
            else
            {
                // Assume either a relative or absolute file path
                if (uri.IsAbsoluteUri && uri.IsFile)
                {
                    path = uri.LocalPath;
                }
                else
                {
                    try
                    {
                        path = Path.GetFullPath(_eula.Source);
                    }
                    catch (Exception)
                    {
                        log.Error($"Cannot determine resource type '{_eula.Source}'. Please review it manually, if possible.");
                        return;
                    }
                }
 
                if (!File.Exists(path))
                {
                    string norm(string x) => x.Trim().Replace('\\', '/');
                    // If the file does not exist, it is likely part of the packagedef, and has not been extracted yet.
                    // Try to extract it to a temporary location and open that instead.
#pragma warning disable CS0618 // Type or member is obsolete
                    using var packageStream = File.OpenRead(_packageDef.Location);
#pragma warning restore CS0618 // Type or member is obsolete
                    using var zip = new ZipArchive(packageStream, ZipArchiveMode.Read);
                    foreach (var part in zip.Entries)
                    {
                        if (norm(part.FullName).Equals(norm(_eula.Source), StringComparison.OrdinalIgnoreCase))
                        {
                            var ext = Path.GetExtension(part.Name);
                            var tmp = Path.GetTempFileName() + ext;
                            path = tmp;
                            var ifs = part.Open();
                            using var ofs = File.Create(path);
                            ifs.CopyTo(ofs);
                            break;
                        }
                    }
                }
 
                if (!File.Exists(path))
                {
                    log.Error($"EULA file '{path}' does not exist.");
                    return;
                }
            }
 
            try
            {
                Process.Start(new ProcessStartInfo()
                {
                    FileName = path,
                    UseShellExecute = true,
                });
            }
            catch (Exception ex)
            {
                log.Error($"Error opening EULA '{path}': {ex.Message}");
                log.Debug(ex);
            }
        }
 
        [Submit]
        [Layout(LayoutMode.FullRow | LayoutMode.FloatBottom)]
        [Display("Answer", Order: 3)]
        public Acceptance Answer { get; set; } = Acceptance.Accept;
 
        public EulaAcceptanceDialog(PackageDef package)
        {
            _packageDef = package;
            _eula = package.EULA;
        }
    }
 
    /// <summary>
    /// End User License Agreement
    /// </summary>
    [XmlType("EULA")]
    public class EULA
    {
        /// <summary>
        /// Unique identifier for this Eula.
        /// </summary>
        [XmlAttribute("Identifier")]
        public string Identifier { get; set; }
        /// <summary>
        /// File or URL where the Eula can be accessed.
        /// </summary>
        [XmlAttribute("Source")]
        public string Source { get; set; }
    }
 
    /// <summary>
    /// Definition of a package file. Contains basic structural information relating to packages.
    /// </summary>
    [DebuggerDisplay("{Name} ({Version.ToString()})")]
    public class PackageDef : PackageIdentifier
    {
        /// <summary>
        /// Holds additional metadata for a package
        /// </summary>
        public Dictionary<string, string> MetaData { get; } = new Dictionary<string, string>();
 
        string loadedHash;
        bool hashVerified;
        const int oldHashLength = 40;
        /// <summary>
        /// The hash of the package. This is based on hashes of each payload file as well as metadata in the package definition.
        /// </summary>
        [DefaultValue(null)]
        public string Hash
        {
            get
            {
                // in OpenTAP 9.18 and earlier weak / invalid hash values were calculated.
                // in 9.19, its fixed, but to distinguish a different length of hashes are used.
                // the previous hash length was always 40.
                
                if (!hashVerified && loadedHash != null)
                {
                    hashVerified = true;
                    if (loadedHash.Length == oldHashLength)
                    {
                        var hash2 = ComputeHash();
                        if (hash2 != null)
                            loadedHash = hash2;
                    }
                }
                
                return loadedHash;
            }
            set
            {
                if (loadedHash == value) return;
                loadedHash = value;
                hashVerified = loadedHash?.Length != oldHashLength;
            }
        }
 
        /// <summary>
        /// A description of this package.
        /// </summary>
        [DefaultValue(null)]
        public string Description { get; set; }
 
        /// <summary>
        /// A list of other packages that this package depends on.
        /// </summary>
        public List<PackageDependency> Dependencies { get; set; } = new List<PackageDependency>();
 
        /// <summary>
        /// If this package originates from a package repository. This is the URL of that repository. Otherwise null
        /// </summary>
        [XmlElement("PackageRepositoryUrl")]
        [DefaultValue(null)]
        [Obsolete("Please use PackageSource instead.")]
        public string Location { get; set; }
 
        /// <summary>
        /// Information of the source of the package definition. 
        /// </summary>
        [DefaultValue(null)]
        public IPackageDefSource PackageSource { get; set; }
        
        /// <summary>
        /// A link to get more information.
        /// </summary>
        [XmlAttribute]
        [DefaultValue(null)]
        public string InfoLink { get; set; }
 
        /// <summary>
        /// The date that the package was build. Defaults to DateTime.MinValue if no date is specified in package.xml
        /// </summary>
        [XmlAttribute]
        public DateTime Date { get; set; }
 
        /// <summary>
        /// The file type of this package. Either 'application' or 'tappackage'. Default is 'tappackage'.
        /// </summary>
        [XmlAttribute]
        [DefaultValue("tappackage")]
        public string FileType { get; set; }
 
        /// <summary>
        /// Name of the owner of the package. There can be multiple owners of a package, in which case this string will have several entries separated with ','.
        /// </summary>
        [DefaultValue(null)]
        public string Owner { get; set; }
 
        /// <summary>
        /// Link to the package source code. This is intended for open sourced projects.
        /// </summary>
        [DefaultValue(null)]
        public string SourceUrl { get; set; }
        
        /// <summary>
        /// Specific open source license. Must be a SPDX identifier, read more at https://spdx.org/licenses/.
        /// </summary>
        [DefaultValue(null)]
        public string SourceLicense { get; set; } 
        
        /// <summary>
        /// Link or path to a Eula which must be accepted in order to use this plugin.
        /// </summary>
        [DefaultValue(null)]
        public EULA EULA { get; set; }
 
        /// <summary>
        /// License(s) required to use this package. During package create all '<see cref="PackageFile.LicenseRequired"/>' attributes from '<see cref="Files"/>' will be concatenated into this property.
        /// Bundle packages (<see cref="Class"/> is 'bundle') can use this property to show licenses that are required by the bundle dependencies. 
        /// </summary>
        [XmlAttribute]
        [DefaultValue("")]
        public string LicenseRequired { get; set; } = "";
 
        /// <summary>
        /// The package class, this can be either 'package', 'bundle' or 'solution'.
        /// </summary>
        [XmlAttribute]
        [DefaultValue("package")]
        public string Class { get; set; }
 
        /// <summary>
        /// Validation objects for validating that the package is correctly installed.
        /// </summary>
        public List<Validation> Validation { get; set; }
 
        internal bool IsBundle()
        {
            return Class.ToLower() == "bundle" || Class.ToLower() == "solution";
        }
 
        internal bool IsSystemWide()
        {
            return Class.ToLower() == "system-wide";
        }
 
        /// <summary>
        /// Name of the group that this package belongs to. Groups can be nested in other groups, in which case this string will have several entries separated with '/' or '\'. May be empty or null. UIs may use this information to show a list of packages as a tree structure.
        /// </summary>
        [XmlAttribute]
        public string Group { get; set; }
        
        /// <summary>
        /// A list of keywords that describe the package. Tags are separated by space or comma.
        /// </summary>
        [XmlAttribute]
        public string Tags { get; set; }
 
        string rawVersion;
        
        /// <summary>
        /// Returns version as a <see cref="SemanticVersion"/>.
        /// </summary>
        /// <returns></returns>
        internal string RawVersion
        {
            get => rawVersion;
            set
            {
                rawVersion = value;
                if (this.Version == null && SemanticVersion.TryParse(value, out var version))
                    Version = version;
            }
        }
 
        /// <summary>
        /// A list of files contained in this package.
        /// </summary>
        public List<PackageFile> Files { get; set; }
 
        /// <summary>
        /// Contains steps that can be executed for this plugin during, or after installation.
        /// </summary>
        public List<ActionStep> PackageActionExtensions { get; set; }
 
        /// <summary>
        /// Creates a new packagedef.
        /// </summary>
        internal PackageDef()
        {
            Files = new List<PackageFile>();
            PackageActionExtensions = new List<ActionStep>();
            OS = "Windows";
            Architecture = CpuArchitecture.AnyCPU;
            
            if (string.IsNullOrWhiteSpace(FileType))
                FileType = "tappackage";
            if (string.IsNullOrWhiteSpace(Class))
                Class = "package";
        }
 
        /// <summary>
        /// Returns a string representation of this PackageDef containing name and version.
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return String.Format("{0}|{1}", Name, Version);
        }
        
        /// <summary>
        /// Loads package definition from a file.
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static PackageDef FromXml(Stream stream)
        {
            stream = ConvertXml(stream);
 
            var serializer = new TapSerializer();
            return (PackageDef)serializer.Deserialize(stream, type: TypeData.FromType(typeof(PackageDef)));
        }
 
        static Stream ConvertXml(Stream stream)
        {
            var root = XElement.Load(stream);
 
            var xns = root.GetDefaultNamespace();
            var filesElement = root.Element(xns.GetName("Files"));
            if (filesElement != null)
            {
                var fileElements = filesElement.Elements(xns.GetName("File"));
                foreach (var file in fileElements)
                {
                    var plugins = file.Element(xns.GetName("Plugins"));
                    if (plugins == null) continue;
 
                    var pluginElements = plugins.Elements(xns.GetName("Plugin"));
                    foreach (var plugin in pluginElements)
                    {
                        if (!plugin.HasElements && !plugin.IsEmpty)
                        {
                            plugin.SetAttributeValue("Type", plugin.Value);
                            var value = plugin.Value;
                            plugin.Value = "";
                        }
                    }
                }
            }
 
            return new MemoryStream(Encoding.UTF8.GetBytes(root.ToString()));
        }
        
        /// <summary>
        /// Writes this package definition to a file.
        /// </summary>
        /// <param name="stream"></param>
        public void SaveTo(Stream stream)
        {
            new TapSerializer().Serialize(stream, this);
        }
 
        
        /// <summary>
        /// Writes this package definition to a file.
        /// </summary>
        public static void SaveManyTo(Stream stream, IEnumerable<PackageDef> packages)
        {
            using var writer = XmlWriter.Create(stream);
            using var _ = TypeData.WithTypeDataCache();
            
            writer.WriteStartDocument();
            writer.WriteStartElement("ArrayOfPackages");
            // Write fragments because we manually insert the start and end of the document.
            // This way, if the stream is outgoing from the process, we avoid having to store all the document
            // in memory. This can be useful as 'packages' may come from a stream itself.
            var serializer = new TapSerializer { WriteFragments = true };
            
            // added batching as a speculative performance improvement.
            foreach (PackageDef package in packages.Batch(32))
            {
                try
                {
                    serializer.Serialize(writer, package);
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }
            }
            
            writer.WriteEndElement();
            writer.Flush();
        }
 
        /// <summary>
        /// Reads a stream of XML into a list of PackageDef objects.
        /// </summary>
        public static IEnumerable<PackageDef> ManyFromXml(Stream stream)
        {
            var root = XElement.Load(stream);
            List<PackageDef> packages = new List<PackageDef>();
 
            Parallel.ForEach(root.Nodes(), node =>
            {
                using (Stream str = new MemoryStream())
                {
                    if (node is XElement nodeElement)
                    {
                        nodeElement.Save(str);
                        str.Seek(0, 0);
                        var package = FromXml(str);
                        if (package != null)
                        {
                            lock (packages)
                            {
                                packages.Add(package);
                            }
                        }
                    }
                    else
                    {
                        throw new XmlException("Invalid XML");
                    }
                }
            });
 
            return packages;
        }
 
        internal static bool TryFromPackage(string path, out PackageDef package)
        {
            try 
            {
                package = FromPackage(path);
                return true;
            }
            catch 
            {
                package = null;
                return false;
            }
        }
 
        /// <summary>
        /// Constructs a PackageDef object to represent a TapPackage package that has already been created.
        /// </summary>
        /// <param name="path">Path to a *.TapPackage file</param>
        public static PackageDef FromPackage(string path)
        {
            string metaFilePath = GetMetadataFromPackage(path);
 
            PackageDef pkgDef;
            using (Stream metaFileStream = new MemoryStream(1000))
            {
                if (!PluginInstaller.UnpackageFile(path, metaFilePath, metaFileStream))
                    throw new Exception("Failed to extract package metadata from package.");
                metaFileStream.Seek(0, SeekOrigin.Begin);
                pkgDef = PackageDef.FromXml(metaFileStream);
            }
            
            //pkgDef.updateVersion();
#pragma warning disable 618
            pkgDef.Location = Path.GetFullPath(path);
#pragma warning restore 618
            pkgDef.PackageSource = new FilePackageDefSource
            {
                PackageFilePath = Path.GetFullPath(path)
            };
            
            return pkgDef;
        }
 
        /// <summary>
        /// Constructs a PackageDef objects to represent each package inside a *.TapPackages file.
        /// </summary>
        public static List<PackageDef> FromPackages(string path)
        {
            var packageList = new List<PackageDef>();
 
            if (Path.GetExtension(path).ToLower() != ".tappackages")
            {
                packageList.Add(FromPackage(path));
                return packageList;
            }
 
            try
            {
                using (var zip = new ZipArchive(File.OpenRead(path), ZipArchiveMode.Read))
                {
                    foreach (var part in zip.Entries)
                    {
                        FileSystemHelper.EnsureDirectoryOf(part.FullName);
                        var instream = part.Open();
                        using (var outstream = File.Create(part.FullName))
                        {
                            var task = instream.CopyToAsync(outstream, 4096, TapThread.Current.AbortToken);
                            ConsoleUtils.PrintProgressTillEnd(task, "Decompressing", () => outstream.Position, () => part.Length);
                        }
                        
                        var package = FromPackage(part.FullName);
                        packageList.Add(package);
 
                        if (File.Exists(part.FullName))
                            File.Delete(part.FullName);
                    }
                }
            }
            catch (InvalidDataException)
            {
                log.Error($"Could not unpackage '{path}'.");
                throw;
            }
 
            return packageList;
        }
 
        /// <summary>
        /// Throws InvalidDataException if the xml in the file does not conform to the schema.
        /// </summary>
        public static void ValidateXml(string path)
        {
            var package = FromXml(path);
            if (string.IsNullOrWhiteSpace(package.Name))
                throw new InvalidDataException("Package Name cannot be empty.");
            if (package.Version == null && package.RawVersion == null)
                throw new InvalidDataException("Package Version cannot be empty.");
            if (string.IsNullOrWhiteSpace(package.OS))
                throw new InvalidDataException("Package OS cannot be empty.");
            if (package.Architecture == CpuArchitecture.Unspecified)
                throw new InvalidDataException("Package Architecture cannot be unspecified.");
        }
 
        /// <summary>
        /// Constructs a PackageDef objects to represent the package definition in the given xml file.
        /// </summary>
        public static PackageDef FromXml(string path)
        {
            using var stream = File.OpenRead(path);
            return FromXml(stream);
        }
        
        /// <summary>
        /// Returns the XML schema for a package definition XML file.
        /// </summary>
        public static XmlSchemaSet GetXmlSchema()
        {
            // Get the schema from the embedded resource:
            var assembly = typeof(OpenTap.Package.Installer).Assembly;
            var resourceName = "OpenTap.Package.PackageSchema.xsd";
            XmlSchema schema;
            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
            {
                schema = XmlSchema.Read(stream, null);
            }
            XmlSchemaSet schemas = new XmlSchemaSet();
            schemas.Add(schema);
            return schemas;
        }
 
        static TraceSource log =  OpenTap.Log.CreateSource("Package");
 
        /// <summary>
        /// Used by ValidateXmlDefinitionFile to write errors to the console formatted so that the PackageTask can parse them.
        /// </summary>
        private static void PrintError(string message, int lineNumber, int linePosition, string path)
        {
            log.Error("{0}({1},{2}): error: {3}", path, lineNumber, linePosition, message);
        }
 
        /// <summary>
        /// Relative path to the directory holding OpenTAP Package definition files
        /// </summary>
        public const string PackageDefDirectory = "Packages";
        /// <summary>
        /// Absolute path to the directory representing the OpenTAP installation dir for system-wide packages
        /// </summary>
        public static string SystemWideInstallationDirectory { get => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Keysight", "Test Automation"); }
 
        /// <summary>
        /// File name for package definition files inside packages.
        /// </summary>
        public const string PackageDefFileName = "package.xml";
 
        internal static string GetDefaultPackageMetadataPath(PackageDef pkg, string target)
        {
            string installationRootDir = target;
            if (pkg.IsSystemWide())
                installationRootDir = PackageDef.SystemWideInstallationDirectory;
            return GetDefaultPackageMetadataPath(pkg.Name, installationRootDir);
        }
 
        internal static string GetDefaultPackageMetadataPath(string name, string installationDir = null)
        {
            if (installationDir == null)
                installationDir = FileSystemHelper.GetCurrentInstallationDirectory();
 
            // don't use Path.Combine, as that might create \ which makes the package unable to install on linux
            return String.Join("/", installationDir, PackageDef.PackageDefDirectory, name, PackageDef.PackageDefFileName); 
        }
 
        /// <summary>
        /// Perform a BFS search to find all package xml's that are not descendants of a .OpenTapIgnore file
        /// </summary>
        /// <param name="packageDir"></param>
        /// <returns></returns>
        private static IEnumerable<string> FindPackageDefinitions(string packageDir)
        {
            var queue = new Queue<string>();
            var results = new List<string>();
            queue.Enqueue(packageDir);
 
            while (queue.Any())
            {
                var dir = queue.Dequeue();
                try
                {
                    var files = Directory.GetFiles(dir, "*", SearchOption.TopDirectoryOnly);
 
                    if (files.Any(f =>
                        string.Equals(Path.GetFileName(f), ".OpenTapIgnore", StringComparison.OrdinalIgnoreCase)))
                        continue;
 
                    var packageXml = files.FirstOrDefault(f =>
                        string.Equals(Path.GetFileName(f), "package.xml", StringComparison.OrdinalIgnoreCase));
 
                    if (packageXml != null)
                        results.Add(packageXml);
 
                    foreach (var subdir in Directory.GetDirectories(dir))
                        queue.Enqueue(subdir);
 
                }
                catch (Exception ex)
                {
                    log.Warning($"Failed reading content of '{dir}'.");
                    log.Debug(ex);
                }
            }
 
            return results;
        }
 
 
        internal static List<string> GetPackageMetadataFilesInTapInstallation(string tapPath)
        {
            List<string> metadatas = new List<string>();
 
            // this way of searching for package.xml files will find them both in their 8.x 
            // location (Package Definitions/<PkgName>.package.xml) and in their new 9.x
            // location (Packages/<PkgName>/package.xml)
 
            // Add 9.x packages in "Packages" folder
            string packageDir = Path.GetFullPath(Path.Combine(tapPath, PackageDefDirectory));
 
            if (Directory.Exists(packageDir))
            {
                var packageDefinitions = FindPackageDefinitions(packageDir);
                metadatas.AddRange(packageDefinitions);
            }
            
 
            // Add backwards compatibility by adding packages in "Package Definitions" folder
            var packageDir8x = Path.GetFullPath(Path.Combine(tapPath, "Package Definitions"));
            if (Directory.Exists(packageDir8x))
                metadatas.AddRange(Directory.GetFiles(packageDir8x, "*.package.xml"));
 
            return metadatas;
        }
 
        internal static List<string> GetSystemWidePackages()
        {
            List<string> metadatas = new List<string>();
 
            // Add 9.x packages in "Packages" folder
            var systemWidePackageDir = Path.Combine(PackageDef.SystemWideInstallationDirectory, PackageDef.PackageDefDirectory);
            if (Directory.Exists(systemWidePackageDir))
                metadatas.AddRange(Directory.GetFiles(systemWidePackageDir, "*" + PackageDef.PackageDefFileName, SearchOption.AllDirectories));
 
            // Add backwards compatibility by adding packages in "Package Definitions" folder
            var systemWidePackageDir8x = Path.Combine(PackageDef.SystemWideInstallationDirectory, "Package Definitions");
            if (Directory.Exists(systemWidePackageDir8x))
                metadatas.AddRange(Directory.GetFiles(systemWidePackageDir8x, "*.package.xml"));
 
            return metadatas;
        }
 
        internal static string GetMetadataFromPackage(string path)
        {
            string metaFilePath = PluginInstaller.FilesInPackage(path)
                .Where(p => p.Contains(PackageDef.PackageDefDirectory) && p.EndsWith(PackageDef.PackageDefFileName))
                .OrderBy(p => p.Length).FirstOrDefault(); // Find the xml file in the most top level
            if (String.IsNullOrEmpty(metaFilePath))
            {
                // for TAP 8.x support, we could remove when 9.0 is final, and packages have been migrated.
                metaFilePath = PluginInstaller.FilesInPackage(path).FirstOrDefault(p => (p.Contains("package/") || p.Contains("Package Definitions/")) && p.EndsWith("package.xml"));
                if (String.IsNullOrEmpty(metaFilePath))
                    throw new IOException("No metadata found in package " + path);
            }
 
            return metaFilePath;
        }
 
        /// <summary>
        /// Computes the hash/signature of the package based on its definition. 
        /// This method relies on hashes of each file. If those are not already part of the definition (they are normally computed when the package is created), this method will try to compute them based on files on the disk.
        /// </summary>
        /// <returns>A base64 encoded SHA1 hash of relevant fields in the package definition</returns>
        public string ComputeHash()
        {
            using MemoryStream str = new MemoryStream();
            using (TextWriter wtr = new StreamWriter(str, Encoding.Default, 4096, true))
            {
                wtr.Write(this.Name);
                wtr.Write(this.Version);
                wtr.Write(this.OS);
                wtr.Write(this.Architecture);
                wtr.Write(this.Date);
                wtr.Write(this.Description);
                wtr.Write(string.Join("", this.Dependencies.OrderBy(d => d.Name).Select(d => d.Name + d.Version)));
                foreach (PackageFile file in this.Files.OrderBy(f => f.FileName))
                {
                    FileHashPackageAction.Hash fileHash =
                        file.CustomData.OfType<FileHashPackageAction.Hash>().FirstOrDefault();
                    if (fileHash != null)
                        wtr.Write(fileHash.Value);
                    else
                        wtr.Write(file.FileName);
                }
            }
 
            str.Seek(0, SeekOrigin.Begin);
            using var algorithm = SHA1.Create();
            var bytes = algorithm.ComputeHash(str);
            return Utils.Base64UrlEncode(bytes);
        }
 
        internal PackageSpecifier GetSpecifier() => new PackageSpecifier(Name, Version.AsExactSpecifier(), Architecture, OS);
 
        internal bool IsValid()
        {
            if (Validation != null)
            {
                foreach (var marker in Validation)
                {
                    if (!marker.IsValid())
                        return false;
 
                }
            }
            return true;
        }
    }
 
    /// <summary>
    /// Base class for package validation objects.
    /// </summary>
    public abstract class Validation
    {
        /// <summary>
        /// Return true if the package installation is valid.
        /// </summary>
        /// <returns>true if the package is correctly installed.</returns>
        public abstract bool IsValid();
    }
 
    /// <summary>
    /// This package validation checks if a file exists.
    /// </summary>
    public class FileExists : Validation
    {
        /// <summary>
        /// The path to the file that have to exist for the package to be correctly installed.
        /// </summary>
        [XmlAttribute]
        public string Path { get; set; }
 
        /// <summary>
        /// Returns true if the file pointed to by Path exists.
        /// </summary>
        /// <returns></returns>
        public override bool IsValid()
        {
            var file = Environment.ExpandEnvironmentVariables(Path);
            return System.IO.File.Exists(file);
        }
    }
 
 
 
    // helper class to ignore namespaces when de-serializing
    internal class NamespaceIgnorantXmlTextReader : XmlTextReader
    {
        public NamespaceIgnorantXmlTextReader(System.IO.Stream stream) : base(stream) { this.Namespaces = false; }
 
        public override string NamespaceURI
        {
            get { return ""; }
        }
    }
 
    /// <summary>
    /// Helper methods used to determine CpuArchitecture and compatibility between them.
    /// </summary>
    public class ArchitectureHelper
    {
        private static CpuArchitecture hostPlatform = CpuArchitecture.Unspecified;
 
        static ArchitectureHelper()
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                // This is a workaround for a bug in RuntimeInformation that calls a non-existing method when run on the .NET4.6.2 Framework.
 
                var def_value = Environment.Is64BitOperatingSystem ? "AMD64" : "x86";
                var str = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE", EnvironmentVariableTarget.Machine) ?? def_value;
 
                switch (str.ToLower())
                {
                    case "arm": hostPlatform = CpuArchitecture.arm; break;
                    case "arm64": hostPlatform = CpuArchitecture.arm64; break;
                    case "amd64": hostPlatform = CpuArchitecture.x64; break;
                    case "x86": hostPlatform = CpuArchitecture.x86; break;
                }
            }
            else
                switch (RuntimeInformation.OSArchitecture)
                {
                    case Architecture.Arm: hostPlatform = CpuArchitecture.arm; break;
                    case Architecture.Arm64: hostPlatform = CpuArchitecture.arm64; break;
                    case Architecture.X64: hostPlatform = CpuArchitecture.x64; break;
                    case Architecture.X86: hostPlatform = CpuArchitecture.x86; break;
                }
        }
 
        /// <summary>
        /// Returns the CPU architecture of the host OS.
        /// </summary>
        public static CpuArchitecture HostArchitecture { get { return hostPlatform; } }
 
        /// <summary>
        /// Returns the architecture that the OpenTAP was compiled for, or the best guess it can give based on the current host architecture and process state.
        /// </summary>
        public static CpuArchitecture GuessBaseArchitecture
        {
            get
            {
                // Try to find the architecture of the base install
                var currentArchitecture = Environment.Is64BitProcess ? CpuArchitecture.x64 : CpuArchitecture.x86; // Assume we are on x86/x86_64
 
                // If we aren't on x86 then just use the host architecture since they are not compatible.
                if ((HostArchitecture == CpuArchitecture.arm) || (HostArchitecture == CpuArchitecture.arm64)) currentArchitecture = HostArchitecture;
 
                // And finally try to use the actual information in the package xml.
                var opentapPackage = Installation.Current.GetOpenTapPackage();
                if (opentapPackage != null)
                    currentArchitecture = opentapPackage.Architecture;
 
                return currentArchitecture;
            }
        }
 
        /// <summary>
        /// Returns true if a host OS can support a plugin with a given CPU architecture.
        /// </summary>
        /// <param name="host">The architecture of the host.</param>
        /// <param name="plugin">The architecture of the plugin.</param>
        /// <returns></returns>
        public static bool CompatibleWith(CpuArchitecture host, CpuArchitecture plugin)
        {
            if (plugin == CpuArchitecture.AnyCPU || host == CpuArchitecture.Unspecified) return true; // TODO: Figure out if this should be allowed in the long term
 
            //if ((host == CpuArchitecture.x64) && (plugin == CpuArchitecture.x86)) return true;
 
            return (host == plugin);
        }
 
        /// <summary>
        /// Returns true if the architectures of two plugins are compatible.
        /// </summary>
        /// <param name="plugin1">The architecture of one of the plugins.</param>
        /// <param name="plugin2">The architecture of the other plugin.</param>
        /// <returns>True, if those two plugins can be used together.</returns>
        public static bool PluginsCompatible(CpuArchitecture plugin1, CpuArchitecture plugin2)
        {
            if (plugin1 == CpuArchitecture.AnyCPU) return true;
            if (plugin2 == CpuArchitecture.AnyCPU) return true;
 
            return plugin1 == plugin2;
        }
    }
}