forked from NuGet/NuGet.Client
-
Notifications
You must be signed in to change notification settings - Fork 7
/
PackageBuilder.cs
1426 lines (1227 loc) · 56.7 KB
/
PackageBuilder.cs
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
// Copyright (c) 2022-Present Chocolatey Software, Inc.
// Copyright (c) 2015-2022 .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml.Linq;
using NuGet.Client;
using NuGet.Common;
using NuGet.Configuration;
using NuGet.ContentModel;
//////////////////////////////////////////////////////////
// Start - Chocolatey Specific Modification
//////////////////////////////////////////////////////////
using Chocolatey.NuGet.Frameworks;
//////////////////////////////////////////////////////////
// End - Chocolatey Specific Modification
//////////////////////////////////////////////////////////
using NuGet.Packaging.Core;
using NuGet.Packaging.PackageCreation.Resources;
using NuGet.RuntimeModel;
using NuGet.Versioning;
namespace NuGet.Packaging
{
//////////////////////////////////////////////////////////
// Start - Chocolatey Specific Modification
//////////////////////////////////////////////////////////
public partial class PackageBuilder : IPackageMetadata
//////////////////////////////////////////////////////////
// End - Chocolatey Specific Modification
//////////////////////////////////////////////////////////
{
private static readonly Uri DefaultUri = new Uri("http://defaultcontainer/");
private static readonly DateTime ZipFormatMinDate = new DateTime(1980, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private static readonly DateTime ZipFormatMaxDate = new DateTime(2107, 12, 31, 23, 59, 58, DateTimeKind.Utc);
internal const string ManifestRelationType = "manifest";
private readonly bool _includeEmptyDirectories;
private readonly bool _deterministic;
private readonly ILogger _logger;
/// <summary>
/// Maximum Icon file size: 1 megabyte
/// </summary>
public const int MaxIconFileSize = 1024 * 1024;
public PackageBuilder(string path, Func<string, string> propertyProvider, bool includeEmptyDirectories)
: this(path, propertyProvider, includeEmptyDirectories, deterministic: false)
{
}
public PackageBuilder(string path, Func<string, string> propertyProvider, bool includeEmptyDirectories, bool deterministic)
: this(path, Path.GetDirectoryName(path), propertyProvider, includeEmptyDirectories, deterministic)
{
}
public PackageBuilder(string path, Func<string, string> propertyProvider, bool includeEmptyDirectories, bool deterministic, ILogger logger)
: this(path, Path.GetDirectoryName(path), propertyProvider, includeEmptyDirectories, deterministic, logger)
{
}
public PackageBuilder(string path, string basePath, Func<string, string> propertyProvider, bool includeEmptyDirectories)
: this(path, basePath, propertyProvider, includeEmptyDirectories, deterministic: false)
{
}
public PackageBuilder(string path, string basePath, Func<string, string> propertyProvider, bool includeEmptyDirectories, bool deterministic, ILogger logger)
: this(path, basePath, propertyProvider, includeEmptyDirectories, deterministic)
{
_logger = logger;
}
public PackageBuilder(string path, string basePath, Func<string, string> propertyProvider, bool includeEmptyDirectories, bool deterministic)
: this(includeEmptyDirectories, deterministic)
{
if (!File.Exists(path))
{
throw new PackagingException(
NuGetLogCode.NU5008,
string.Format(CultureInfo.CurrentCulture, Strings.ErrorManifestFileNotFound, path ?? "null"));
}
using (Stream stream = File.OpenRead(path))
{
ReadManifest(stream, basePath, propertyProvider);
}
}
public PackageBuilder(Stream stream, string basePath)
: this(stream, basePath, null)
{
}
public PackageBuilder(Stream stream, string basePath, Func<string, string> propertyProvider)
: this()
{
ReadManifest(stream, basePath, propertyProvider);
}
public PackageBuilder(bool deterministic) :
this(includeEmptyDirectories: false, deterministic: deterministic)
{
}
public PackageBuilder()
: this(includeEmptyDirectories: false, deterministic: false)
{
}
public PackageBuilder(bool deterministic, ILogger logger)
: this(includeEmptyDirectories: false, deterministic: deterministic, logger)
{
}
private PackageBuilder(bool includeEmptyDirectories, bool deterministic)
: this(includeEmptyDirectories: false, deterministic: deterministic, logger: NullLogger.Instance)
{
}
private PackageBuilder(bool includeEmptyDirectories, bool deterministic, ILogger logger)
{
_includeEmptyDirectories = includeEmptyDirectories;
_deterministic = false; // fix in https://github.com/NuGet/Home/issues/8601
_logger = logger;
Files = new Collection<IPackageFile>();
DependencyGroups = new Collection<PackageDependencyGroup>();
FrameworkReferences = new Collection<FrameworkAssemblyReference>();
FrameworkReferenceGroups = new Collection<FrameworkReferenceGroup>();
ContentFiles = new Collection<ManifestContentFiles>();
PackageAssemblyReferences = new Collection<PackageReferenceSet>();
PackageTypes = new Collection<PackageType>();
Authors = new HashSet<string>();
Owners = new HashSet<string>();
Tags = new HashSet<string>();
TargetFrameworks = new List<NuGetFramework>();
// Just like parameter replacements, these are also case insensitive, for consistency.
Properties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
//////////////////////////////////////////////////////////
// Start - Chocolatey Specific Modification
//////////////////////////////////////////////////////////
FinishContruction();
//////////////////////////////////////////////////////////
// End - Chocolatey Specific Modification
//////////////////////////////////////////////////////////
}
public string Id
{
get;
set;
}
public NuGetVersion Version
{
get;
set;
}
public RepositoryMetadata Repository { get; set; }
public LicenseMetadata LicenseMetadata { get; set; }
public bool HasSnapshotVersion
{
get;
set;
}
public string Title
{
get;
set;
}
public ISet<string> Authors
{
get;
private set;
}
public ISet<string> Owners
{
get;
private set;
}
public Uri IconUrl
{
get;
set;
}
public string Icon
{
get;
set;
}
public Uri LicenseUrl
{
get;
set;
}
public Uri ProjectUrl
{
get;
set;
}
public bool RequireLicenseAcceptance
{
get;
set;
}
public bool EmitRequireLicenseAcceptance
{
get;
set;
} = true;
public bool Serviceable
{
get;
set;
}
public bool DevelopmentDependency
{
get;
set;
}
public string Description
{
get;
set;
}
public string Summary
{
get;
set;
}
public string ReleaseNotes
{
get;
set;
}
public string Language
{
get;
set;
}
public string OutputName
{
get;
set;
}
public ISet<string> Tags
{
get;
private set;
}
public string Readme { get; set; }
/// <summary>
/// Exposes the additional properties extracted by the metadata
/// extractor or received from the command line.
/// </summary>
public Dictionary<string, string> Properties
{
get;
private set;
}
public string Copyright
{
get;
set;
}
public Collection<PackageDependencyGroup> DependencyGroups
{
get;
private set;
}
public ICollection<IPackageFile> Files
{
get;
private set;
}
public Collection<FrameworkAssemblyReference> FrameworkReferences
{
get;
private set;
}
public Collection<FrameworkReferenceGroup> FrameworkReferenceGroups
{
get;
private set;
}
public IList<NuGetFramework> TargetFrameworks
{
get;
set;
}
/// <summary>
/// ContentFiles section from the manifest for content v2
/// </summary>
public ICollection<ManifestContentFiles> ContentFiles
{
get;
private set;
}
public ICollection<PackageReferenceSet> PackageAssemblyReferences
{
get;
set;
}
public ICollection<PackageType> PackageTypes
{
get;
set;
}
IEnumerable<string> IPackageMetadata.Authors
{
get
{
return Authors;
}
}
IEnumerable<string> IPackageMetadata.Owners
{
get
{
return Owners;
}
}
string IPackageMetadata.Tags
{
get
{
return string.Join(" ", Tags);
}
}
IEnumerable<PackageReferenceSet> IPackageMetadata.PackageAssemblyReferences
{
get
{
return PackageAssemblyReferences;
}
}
IEnumerable<PackageDependencyGroup> IPackageMetadata.DependencyGroups
{
get
{
return DependencyGroups;
}
}
IEnumerable<FrameworkAssemblyReference> IPackageMetadata.FrameworkReferences
{
get
{
return FrameworkReferences;
}
}
IEnumerable<ManifestContentFiles> IPackageMetadata.ContentFiles
{
get
{
return ContentFiles;
}
}
IEnumerable<PackageType> IPackageMetadata.PackageTypes
{
get
{
return PackageTypes;
}
}
IEnumerable<FrameworkReferenceGroup> IPackageMetadata.FrameworkReferenceGroups => FrameworkReferenceGroups;
public Version MinClientVersion
{
get;
set;
}
public void Save(Stream stream)
{
// Make sure we're saving a valid package id
PackageIdValidator.ValidatePackageId(Id);
// Throw if the package doesn't contain any dependencies nor content
if (!Files.Any() && !DependencyGroups.SelectMany(d => d.Packages).Any() && !FrameworkReferences.Any() && !FrameworkReferenceGroups.Any())
{
throw new PackagingException(NuGetLogCode.NU5017, NuGetResources.CannotCreateEmptyPackage);
}
ValidateDependencies(Version, DependencyGroups);
ValidateFilesUnique(Files);
ValidateReferenceAssemblies(Files, PackageAssemblyReferences);
ValidateFrameworkAssemblies(FrameworkReferences, FrameworkReferenceGroups);
ValidateLicenseFile(Files, LicenseMetadata);
ValidateIconFile(Files, Icon);
ValidateFileFrameworks(Files);
ValidateReadmeFile(Files, Readme);
using (var package = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true))
{
string psmdcpPath = $"package/services/metadata/core-properties/{CalcPsmdcpName()}.psmdcp";
// Validate and write the manifest
WriteManifest(package, DetermineMinimumSchemaVersion(Files, DependencyGroups), psmdcpPath);
// Write the files to the package
HashSet<string> filesWithoutExtensions = new HashSet<string>();
var extensions = WriteFiles(package, filesWithoutExtensions);
extensions.Add("nuspec");
WriteOpcContentTypes(package, extensions, filesWithoutExtensions);
WriteOpcPackageProperties(package, psmdcpPath);
}
}
private static byte[] ReadAllBytes(Stream stream)
{
using (var ms = new MemoryStream())
{
stream.CopyTo(ms);
return ms.ToArray();
}
}
private string CalcPsmdcpName()
{
if (_deterministic)
{
using (var hashFunc = new Sha512HashFunction())
{
foreach (var file in Files)
{
var data = ReadAllBytes(file.GetStream());
hashFunc.Update(data, 0, data.Length);
}
return EncodeHexString(hashFunc.GetHashBytes()).Substring(0, 32);
}
}
else
{
return Guid.NewGuid().ToString("N", provider: null);
}
}
private static readonly char[] HexValues = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
// Reference https://github.com/dotnet/corefx/blob/2c2e4a599889652ec579a870054b0f8915ea70fd/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Utils.cs#L736
internal static string EncodeHexString(byte[] sArray)
{
uint start = 0;
uint end = (uint)sArray.Length;
string result = null;
if (sArray != null)
{
char[] hexOrder = new char[(end - start) * 2];
uint digit;
for (uint i = start, j = 0; i < end; i++)
{
digit = (uint)((sArray[i] & 0xf0) >> 4);
hexOrder[j++] = HexValues[digit];
digit = (uint)(sArray[i] & 0x0f);
hexOrder[j++] = HexValues[digit];
}
result = new string(hexOrder);
}
return result;
}
private static string CreatorInfo()
{
List<string> creatorInfo = new List<string>();
var assembly = typeof(PackageBuilder).GetTypeInfo().Assembly;
creatorInfo.Add(assembly.FullName);
#if !IS_CORECLR // CORECLR_TODO: Environment.OSVersion
creatorInfo.Add(Environment.OSVersion.ToString());
#endif
var attribute = assembly.GetCustomAttributes<System.Runtime.Versioning.TargetFrameworkAttribute>().FirstOrDefault();
if (attribute != null)
{
creatorInfo.Add(attribute.FrameworkDisplayName);
}
return string.Join(";", creatorInfo);
}
private static int DetermineMinimumSchemaVersion(
ICollection<IPackageFile> Files,
ICollection<PackageDependencyGroup> package)
{
if (HasContentFilesV2(Files) || HasIncludeExclude(package))
{
// version 5
return ManifestVersionUtility.XdtTransformationVersion;
}
if (HasXdtTransformFile(Files))
{
// version 5
return ManifestVersionUtility.XdtTransformationVersion;
}
if (RequiresV4TargetFrameworkSchema(Files))
{
// version 4
return ManifestVersionUtility.TargetFrameworkSupportForDependencyContentsAndToolsVersion;
}
return ManifestVersionUtility.DefaultVersion;
}
private static bool RequiresV4TargetFrameworkSchema(ICollection<IPackageFile> files)
{
// check if any file under Content or Tools has TargetFramework defined
bool hasContentOrTool = files.Any(
f => f.NuGetFramework != null &&
!f.NuGetFramework.IsUnsupported &&
(f.Path.StartsWith(PackagingConstants.Folders.Content + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) ||
f.Path.StartsWith(PackagingConstants.Folders.Tools + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)));
if (hasContentOrTool)
{
return true;
}
// now check if the Lib folder has any empty framework folder
bool hasEmptyLibFolder = files.Any(
f => f.NuGetFramework != null &&
f.Path.StartsWith(PackagingConstants.Folders.Lib + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) &&
f.EffectivePath == PackagingConstants.PackageEmptyFileName);
return hasEmptyLibFolder;
}
private static bool HasContentFilesV2(ICollection<IPackageFile> contentFiles)
{
return contentFiles.Any(file =>
file.Path != null &&
file.Path.StartsWith(PackagingConstants.Folders.ContentFiles + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase));
}
private static bool HasIncludeExclude(IEnumerable<PackageDependencyGroup> dependencyGroups)
{
return dependencyGroups.Any(dependencyGroup =>
dependencyGroup.Packages
.Any(dependency => dependency.Include != null || dependency.Exclude != null));
}
private static bool HasXdtTransformFile(ICollection<IPackageFile> contentFiles)
{
return contentFiles.Any(file =>
file.Path != null &&
file.Path.StartsWith(PackagingConstants.Folders.Content + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) &&
(file.Path.EndsWith(".install.xdt", StringComparison.OrdinalIgnoreCase) ||
file.Path.EndsWith(".uninstall.xdt", StringComparison.OrdinalIgnoreCase)));
}
private static void ValidateDependencies(SemanticVersion version,
IEnumerable<PackageDependencyGroup> dependencies)
{
var frameworksMissingPlatformVersion = new HashSet<string>(dependencies
.Select(group => group.TargetFramework)
.Where(groupFramework => groupFramework.HasPlatform && groupFramework.PlatformVersion == FrameworkConstants.EmptyVersion)
.Select(framework => framework.GetShortFolderName()));
if (frameworksMissingPlatformVersion.Any())
{
throw new PackagingException(NuGetLogCode.NU1012, string.Format(CultureInfo.CurrentCulture, Strings.MissingTargetPlatformVersionsFromDependencyGroups, string.Join(", ", frameworksMissingPlatformVersion.OrderBy(str => str))));
}
if (version == null)
{
// We have independent validation for null-versions.
return;
}
foreach (var dep in dependencies.SelectMany(s => s.Packages))
{
PackageIdValidator.ValidatePackageId(dep.Id);
}
}
public static void ValidateReferenceAssemblies(IEnumerable<IPackageFile> files, IEnumerable<PackageReferenceSet> packageAssemblyReferences)
{
var frameworksMissingPlatformVersion = new HashSet<string>(packageAssemblyReferences
.Select(group => group.TargetFramework)
.Where(groupFramework => groupFramework != null && groupFramework.HasPlatform && groupFramework.PlatformVersion == FrameworkConstants.EmptyVersion)
.Select(framework => framework.GetShortFolderName()));
if (frameworksMissingPlatformVersion.Any())
{
throw new PackagingException(NuGetLogCode.NU1012, string.Format(CultureInfo.CurrentCulture, Strings.MissingTargetPlatformVersionsFromReferenceGroups, string.Join(", ", frameworksMissingPlatformVersion.OrderBy(str => str))));
}
var libFiles = new HashSet<string>(from file in files
where !string.IsNullOrEmpty(file.Path) && file.Path.StartsWith("lib", StringComparison.OrdinalIgnoreCase)
select Path.GetFileName(file.Path), StringComparer.OrdinalIgnoreCase);
foreach (var reference in packageAssemblyReferences.SelectMany(p => p.References))
{
if (!libFiles.Contains(reference) &&
!libFiles.Contains(reference + ".dll") &&
!libFiles.Contains(reference + ".exe") &&
!libFiles.Contains(reference + ".winmd"))
{
throw new PackagingException(NuGetLogCode.NU5018, string.Format(CultureInfo.CurrentCulture, NuGetResources.Manifest_InvalidReference, reference));
}
}
}
private static void ValidateFrameworkAssemblies(IEnumerable<FrameworkAssemblyReference> references, IEnumerable<FrameworkReferenceGroup> referenceGroups)
{
// Check standalone references
var frameworksMissingPlatformVersion = new HashSet<string>(references
.SelectMany(reference => reference.SupportedFrameworks)
.Where(framework => framework.HasPlatform && framework.PlatformVersion == FrameworkConstants.EmptyVersion)
.Select(framework => framework.GetShortFolderName())
);
if (frameworksMissingPlatformVersion.Any())
{
throw new PackagingException(NuGetLogCode.NU1012, string.Format(CultureInfo.CurrentCulture, Strings.MissingTargetPlatformVersionsFromFrameworkAssemblyReferences, string.Join(", ", frameworksMissingPlatformVersion.OrderBy(str => str))));
}
// Check reference groups too
frameworksMissingPlatformVersion = new HashSet<string>(referenceGroups
.Select(group => group.TargetFramework)
.Where(groupFramework => groupFramework.HasPlatform && groupFramework.PlatformVersion == FrameworkConstants.EmptyVersion)
.Select(framework => framework.GetShortFolderName()));
if (frameworksMissingPlatformVersion.Any())
{
throw new PackagingException(NuGetLogCode.NU1012, string.Format(CultureInfo.CurrentCulture, Strings.MissingTargetPlatformVersionsFromFrameworkAssemblyGroups, string.Join(", ", frameworksMissingPlatformVersion.OrderBy(str => str))));
}
}
/// <summary>Looks for the specified file within the package</summary>
/// <param name="filePath">The file path to search for</param>
/// <param name="packageFiles">The list of files to search within</param>
/// <param name="filePathIncorrectCase">If the file was not found, this will be a path which almost matched but had the incorrect case</param>
/// <returns>An <see cref="IPackageFile"/> matching the specified path or <c>null</c></returns>
private static IPackageFile FindFileInPackage(string filePath, IEnumerable<IPackageFile> packageFiles, out string filePathIncorrectCase)
{
filePathIncorrectCase = null;
var strippedFilePath = PathUtility.StripLeadingDirectorySeparators(filePath);
foreach (var packageFile in packageFiles)
{
var strippedPackageFilePath = PathUtility.StripLeadingDirectorySeparators(packageFile.Path);
// This must use a case-sensitive string comparison, even on systems where file paths are normally case-sensitive.
// This is because Zip files are treated as case-sensitive. (See https://github.com/NuGet/Home/issues/9817)
if (strippedPackageFilePath.Equals(strippedFilePath, StringComparison.Ordinal))
{
// Found the requested file in the package
filePathIncorrectCase = null;
return packageFile;
}
// Check for files that exist with the wrong file casing
else if (filePathIncorrectCase is null && strippedPackageFilePath.Equals(strippedFilePath, StringComparison.OrdinalIgnoreCase))
{
filePathIncorrectCase = strippedPackageFilePath;
}
}
// We searched all of the package files and didn't find what we were looking for
return null;
}
private void ValidateFilesUnique(IEnumerable<IPackageFile> files)
{
var seen = new HashSet<string>(StringComparer.Ordinal);
var duplicates = new HashSet<string>(StringComparer.Ordinal);
foreach (string destination in files.Where(t => t.Path != null).Select(t => PathUtility.GetPathWithDirectorySeparator(t.Path)))
{
if (!seen.Add(destination))
{
duplicates.Add(destination);
}
}
if (duplicates.Any())
{
throw new PackagingException(NuGetLogCode.NU5050, string.Format(CultureInfo.CurrentCulture, NuGetResources.FoundDuplicateFile, string.Join(", ", duplicates)));
}
}
private void ValidateLicenseFile(IEnumerable<IPackageFile> files, LicenseMetadata licenseMetadata)
{
if (!PackageTypes.Contains(PackageType.SymbolsPackage) && licenseMetadata?.Type == LicenseType.File)
{
var ext = Path.GetExtension(licenseMetadata.License);
if (!string.IsNullOrEmpty(ext) &&
!ext.Equals(".txt", StringComparison.OrdinalIgnoreCase) &&
!ext.Equals(".md", StringComparison.OrdinalIgnoreCase))
{
throw new PackagingException(NuGetLogCode.NU5031, string.Format(CultureInfo.CurrentCulture, NuGetResources.Manifest_LicenseFileExtensionIsInvalid, licenseMetadata.License));
}
if (FindFileInPackage(licenseMetadata.License, files, out var licenseFilePathWithIncorrectCase) is null)
{
string errorMessage;
if (licenseFilePathWithIncorrectCase is null)
{
errorMessage = string.Format(CultureInfo.CurrentCulture, NuGetResources.Manifest_LicenseFileIsNotInNupkg, licenseMetadata.License);
}
else
{
errorMessage = string.Format(CultureInfo.CurrentCulture, NuGetResources.Manifest_LicenseFileIsNotInNupkgWithHint, licenseMetadata.License, licenseFilePathWithIncorrectCase);
}
throw new PackagingException(NuGetLogCode.NU5030, errorMessage);
}
}
}
/// <summary>
/// Given a list of resolved files,
/// determine which file will be used as the icon file and validate its size and extension.
/// </summary>
/// <param name="files">Files resolved from the file entries in the nuspec</param>
/// <param name="iconPath">icon entry found in the .nuspec</param>
/// <exception cref="PackagingException">When a validation rule is not met</exception>
private void ValidateIconFile(IEnumerable<IPackageFile> files, string iconPath)
{
if (!PackageTypes.Contains(PackageType.SymbolsPackage) && !string.IsNullOrEmpty(iconPath))
{
var ext = Path.GetExtension(iconPath);
if (string.IsNullOrEmpty(ext) || (
!ext.Equals(".jpeg", StringComparison.OrdinalIgnoreCase) &&
!ext.Equals(".jpg", StringComparison.OrdinalIgnoreCase) &&
!ext.Equals(".png", StringComparison.OrdinalIgnoreCase)))
{
throw new PackagingException(
NuGetLogCode.NU5045,
string.Format(CultureInfo.CurrentCulture, NuGetResources.IconInvalidExtension, iconPath));
}
// Validate entry
IPackageFile iconFile = FindFileInPackage(iconPath, files, out var iconPathWithIncorrectCase);
if (iconFile is null)
{
string errorMessage;
if (iconPathWithIncorrectCase is null)
{
errorMessage = string.Format(CultureInfo.CurrentCulture, NuGetResources.IconNoFileElement, iconPath);
}
else
{
errorMessage = string.Format(CultureInfo.CurrentCulture, NuGetResources.IconNoFileElementWithHint, iconPath, iconPathWithIncorrectCase);
}
throw new PackagingException(NuGetLogCode.NU5046, errorMessage);
}
try
{
// Validate Icon open file
using (var iconStream = iconFile.GetStream())
{
// Validate file size
long fileSize = iconStream.Length;
if (fileSize > MaxIconFileSize)
{
throw new PackagingException(Common.NuGetLogCode.NU5047, NuGetResources.IconMaxFileSizeExceeded);
}
if (fileSize == 0)
{
throw new PackagingException(Common.NuGetLogCode.NU5047, NuGetResources.IconErrorEmpty);
}
}
}
catch (FileNotFoundException e)
{
throw new PackagingException(
NuGetLogCode.NU5046,
string.Format(CultureInfo.CurrentCulture, NuGetResources.IconCannotOpenFile, iconPath, e.Message));
}
}
}
private static void ValidateFileFrameworks(IEnumerable<IPackageFile> files)
{
var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var file in files.Where(t => t.Path != null).Select(t => PathUtility.GetPathWithDirectorySeparator(t.Path)))
{
set.Add(file);
}
var managedCodeConventions = new ManagedCodeConventions(new RuntimeGraph());
var collection = new ContentItemCollection();
collection.Load(set.Select(path => path.Replace('\\', '/')).ToArray());
var patterns = managedCodeConventions.Patterns;
var frameworkPatterns = new List<PatternSet>()
{
patterns.RuntimeAssemblies,
patterns.CompileRefAssemblies,
patterns.CompileLibAssemblies,
patterns.NativeLibraries,
patterns.ResourceAssemblies,
patterns.MSBuildFiles,
patterns.ContentFiles,
patterns.ToolsAssemblies,
patterns.EmbedAssemblies,
patterns.MSBuildTransitiveFiles
};
var warnPaths = new HashSet<string>();
var frameworksMissingPlatformVersion = new HashSet<string>();
List<ContentItemGroup> targetedItemGroups = new();
foreach (var pattern in frameworkPatterns)
{
targetedItemGroups.Clear();
ContentExtractor.GetContentForPattern(collection, pattern, targetedItemGroups);
foreach (ContentItemGroup group in targetedItemGroups)
{
foreach (ContentItem item in group.Items)
{
var framework = (NuGetFramework)item.Properties["tfm"];
if (framework == null)
{
continue;
}
if (framework.HasPlatform && framework.PlatformVersion == FrameworkConstants.EmptyVersion)
{
frameworksMissingPlatformVersion.Add(framework.GetShortFolderName());
}
}
}
}
if (frameworksMissingPlatformVersion.Any())
{
throw new PackagingException(NuGetLogCode.NU1012, string.Format(CultureInfo.CurrentCulture, Strings.MissingTargetPlatformVersionsFromIncludedFiles, string.Join(", ", frameworksMissingPlatformVersion.OrderBy(str => str))));
}
}
/// <summary>
/// Validate that the readme file is of the correct size/type and can be opened properly except for Symbol packages.
/// </summary>
/// <param name="files">Files resolved from the file entries in the nuspec</param>
/// <param name="readmePath">readmepath found in the .nuspec</param>
/// <exception cref="PackagingException">When a validation rule is not met</exception>
private void ValidateReadmeFile(IEnumerable<IPackageFile> files, string readmePath)
{
if (!PackageTypes.Contains(PackageType.SymbolsPackage) && !string.IsNullOrEmpty(readmePath))
{
// Validate readme extension
var extension = Path.GetExtension(readmePath);
if (!string.IsNullOrEmpty(extension) &&
!extension.Equals(NuGetConstants.ReadmeExtension, StringComparison.OrdinalIgnoreCase))
{
throw new PackagingException(
NuGetLogCode.NU5038,
string.Format(CultureInfo.CurrentCulture, NuGetResources.ReadmeFileExtensionIsInvalid, readmePath));
}
// Validate entry
var readmePathStripped = PathUtility.StripLeadingDirectorySeparators(readmePath);
var readmeFileList = files.Where(f =>
readmePathStripped.Equals(
PathUtility.StripLeadingDirectorySeparators(f.Path),
PathUtility.GetStringComparisonBasedOnOS()));
if (!readmeFileList.Any())
{
throw new PackagingException(
NuGetLogCode.NU5039,
string.Format(CultureInfo.CurrentCulture, NuGetResources.ReadmeNoFileElement, readmePath));
}
IPackageFile readmeFile = readmeFileList.First();
try
{
// Validate Readme open file
using (var readmeStream = readmeFile.GetStream())
{
// Validate file size is not 0
long fileSize = readmeStream.Length;
if (fileSize == 0)
{
throw new PackagingException(
NuGetLogCode.NU5040,
string.Format(CultureInfo.CurrentCulture, NuGetResources.ReadmeErrorEmpty, readmePath));
}
}
}
catch (FileNotFoundException e)
{
throw new PackagingException(
NuGetLogCode.NU5041,
string.Format(CultureInfo.CurrentCulture, NuGetResources.ReadmeCannotOpenFile, readmePath, e.Message));
}
}
}
private void ReadManifest(Stream stream, string basePath, Func<string, string> propertyProvider)
{
// Deserialize the document and extract the metadata
Manifest manifest = Manifest.ReadFrom(stream, propertyProvider, validateSchema: true);
Populate(manifest.Metadata);
// If there's no base path then ignore the files node
if (basePath != null)
{
if (!manifest.HasFilesNode)
{
AddFiles(basePath, @"**\*", null);
}
else
{
PopulateFiles(basePath, manifest.Files);
}
}
}
public void Populate(ManifestMetadata manifestMetadata)
{
IPackageMetadata metadata = manifestMetadata;
Id = metadata.Id;
Version = metadata.Version;
Title = metadata.Title;
Authors.AddRange(metadata.Authors);
Owners.AddRange(metadata.Owners);
IconUrl = metadata.IconUrl;
LicenseUrl = metadata.LicenseUrl;
ProjectUrl = metadata.ProjectUrl;
RequireLicenseAcceptance = metadata.RequireLicenseAcceptance;
DevelopmentDependency = metadata.DevelopmentDependency;
Serviceable = metadata.Serviceable;
Description = metadata.Description;
Summary = metadata.Summary;
ReleaseNotes = metadata.ReleaseNotes;
Language = metadata.Language;
Copyright = metadata.Copyright;
MinClientVersion = metadata.MinClientVersion;
Repository = metadata.Repository;
ContentFiles = new Collection<ManifestContentFiles>(manifestMetadata.ContentFiles.ToList());
LicenseMetadata = metadata.LicenseMetadata;
Icon = metadata.Icon;
Readme = metadata.Readme;
if (metadata.Tags != null)
{