-
Notifications
You must be signed in to change notification settings - Fork 749
Expand file tree
/
Copy pathPackTaskLogic.cs
More file actions
1113 lines (975 loc) · 50.7 KB
/
PackTaskLogic.cs
File metadata and controls
1113 lines (975 loc) · 50.7 KB
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) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using NuGet.Commands;
using NuGet.Common;
using NuGet.Frameworks;
using NuGet.LibraryModel;
using NuGet.Packaging;
using NuGet.Packaging.Core;
using NuGet.Packaging.Licenses;
using NuGet.ProjectModel;
using NuGet.Versioning;
using PackageSpecificWarningProperties = NuGet.Commands.PackCommand.PackageSpecificWarningProperties;
namespace NuGet.Build.Tasks.Pack
{
public class PackTaskLogic : IPackTaskLogic
{
private const string IdentityProperty = "Identity";
private PackageSpecificWarningProperties _packageSpecificWarningProperties;
public PackArgs GetPackArgs(IPackTaskRequest<IMSBuildItem> request)
{
var packArgs = new PackArgs
{
InstallPackageToOutputPath = request.InstallPackageToOutputPath,
OutputFileNamesWithoutVersion = request.OutputFileNamesWithoutVersion,
OutputDirectory = request.PackageOutputPath,
Serviceable = request.Serviceable,
Tool = request.IsTool,
Symbols = request.IncludeSymbols,
SymbolPackageFormat = PackArgs.GetSymbolPackageFormat(request.SymbolPackageFormat),
BasePath = request.NuspecBasePath,
NoPackageAnalysis = request.NoPackageAnalysis,
NoDefaultExcludes = request.NoDefaultExcludes,
WarningProperties = WarningProperties.GetWarningProperties(request.TreatWarningsAsErrors, request.WarningsAsErrors, request.NoWarn, request.WarningsNotAsErrors),
PackTargetArgs = new MSBuildPackTargetArgs()
};
packArgs.Logger = new PackCollectorLogger(request.Logger, packArgs.WarningProperties, _packageSpecificWarningProperties);
if (request.MinClientVersion != null)
{
Version version;
if (!Version.TryParse(request.MinClientVersion, out version))
{
throw new PackagingException(NuGetLogCode.NU5022, string.Format(
CultureInfo.CurrentCulture,
Strings.InvalidMinClientVersion,
request.MinClientVersion));
}
packArgs.MinClientVersion = version;
}
LockFile assetsFile = GetAssetsFile(request);
var aliases = new Dictionary<string, string>();
foreach (var tfm in assetsFile.PackageSpec.TargetFrameworks)
{
aliases[tfm.TargetAlias] = tfm.FrameworkName.GetShortFolderName();
}
InitCurrentDirectoryAndFileName(request, packArgs);
InitNuspecOutputPath(request, packArgs);
PackCommandRunner.SetupCurrentDirectory(packArgs);
if (!string.IsNullOrEmpty(request.NuspecFile))
{
SetPackArgsPropertiesFromNuspecProperties(packArgs, request.NuspecProperties);
}
else
{
// This only needs to happen when packing via csproj, not nuspec.
packArgs.PackTargetArgs.AllowedOutputExtensionsInPackageBuildOutputFolder = InitOutputExtensions(request.AllowedOutputExtensionsInPackageBuildOutputFolder);
packArgs.PackTargetArgs.AllowedOutputExtensionsInSymbolsPackageBuildOutputFolder = InitOutputExtensions(request.AllowedOutputExtensionsInSymbolsPackageBuildOutputFolder);
packArgs.PackTargetArgs.TargetPathsToAssemblies = InitLibFiles(request.BuildOutputInPackage, aliases);
packArgs.PackTargetArgs.TargetPathsToSymbols = InitLibFiles(request.TargetPathsToSymbols, aliases);
packArgs.PackTargetArgs.AssemblyName = request.AssemblyName;
packArgs.PackTargetArgs.IncludeBuildOutput = request.IncludeBuildOutput;
packArgs.PackTargetArgs.BuildOutputFolder = request.BuildOutputFolders;
packArgs.PackTargetArgs.TargetFrameworks = ParseFrameworks(request, aliases);
if (request.IncludeSource)
{
packArgs.PackTargetArgs.SourceFiles = GetSourceFiles(request, packArgs.CurrentDirectory);
packArgs.Symbols = request.IncludeSource;
}
var contentFiles = ProcessContentToIncludeInPackage(request, packArgs);
packArgs.PackTargetArgs.ContentFiles = contentFiles;
}
return packArgs;
}
public PackageBuilder GetPackageBuilder(IPackTaskRequest<IMSBuildItem> request)
{
// Load the assets JSON file produced by restore.
var assetsFilePath = Path.Combine(request.RestoreOutputPath, LockFileFormat.AssetsFileName);
if (!File.Exists(assetsFilePath))
{
throw new PackagingException(NuGetLogCode.NU5023, string.Format(
CultureInfo.CurrentCulture,
Strings.AssetsFileNotFound,
assetsFilePath));
}
var builder = new PackageBuilder(request.Deterministic, request.Logger)
{
Id = request.PackageId,
Description = request.Description,
Title = request.Title,
Copyright = request.Copyright,
ReleaseNotes = request.ReleaseNotes,
RequireLicenseAcceptance = request.RequireLicenseAcceptance,
EmitRequireLicenseAcceptance = request.RequireLicenseAcceptance,
PackageTypes = ParsePackageTypes(request)
};
if (request.DevelopmentDependency)
{
builder.DevelopmentDependency = true;
}
if (request.PackageVersion != null)
{
NuGetVersion version;
if (!NuGetVersion.TryParse(request.PackageVersion, out version))
{
throw new PackagingException(NuGetLogCode.NU5024, string.Format(
CultureInfo.CurrentCulture,
Strings.InvalidPackageVersion,
request.PackageVersion));
}
builder.Version = version;
}
else
{
builder.Version = new NuGetVersion("1.0.0");
}
if (request.Authors != null)
{
builder.Authors.AddRange(request.Authors);
}
if (request.Tags != null)
{
builder.Tags.AddRange(request.Tags);
}
Uri tempUri;
if (Uri.TryCreate(request.LicenseUrl, UriKind.Absolute, out tempUri))
{
builder.LicenseUrl = tempUri;
}
if (Uri.TryCreate(request.ProjectUrl, UriKind.Absolute, out tempUri))
{
builder.ProjectUrl = tempUri;
}
if (Uri.TryCreate(request.IconUrl, UriKind.Absolute, out tempUri))
{
builder.IconUrl = tempUri;
}
if (!string.IsNullOrEmpty(request.RepositoryUrl) || !string.IsNullOrEmpty(request.RepositoryType))
{
builder.Repository = new RepositoryMetadata(
request.RepositoryType,
request.RepositoryUrl,
request.RepositoryBranch,
request.RepositoryCommit);
}
builder.LicenseMetadata = BuildLicenseMetadata(request);
builder.Icon = request.PackageIcon;
builder.Readme = request.Readme;
if (request.MinClientVersion != null)
{
Version version;
if (!Version.TryParse(request.MinClientVersion, out version))
{
throw new PackagingException(NuGetLogCode.NU5022, string.Format(
CultureInfo.CurrentCulture,
Strings.InvalidMinClientVersion,
request.MinClientVersion));
}
builder.MinClientVersion = version;
}
// The assets file is necessary for project and package references. Pack should not do any traversal,
// so we leave that work up to restore (which produces the assets file).
var lockFileFormat = new LockFileFormat();
var assetsFile = lockFileFormat.Read(assetsFilePath);
if (assetsFile.PackageSpec == null)
{
throw new PackagingException(NuGetLogCode.NU5025, string.Format(
CultureInfo.CurrentCulture,
Strings.AssetsFileDoesNotHaveValidPackageSpec,
assetsFilePath));
}
var projectRefToVersionMap = new Dictionary<string, string>(PathUtility.GetStringComparerBasedOnOS());
if (request.ProjectReferencesWithVersions != null && request.ProjectReferencesWithVersions.Any())
{
projectRefToVersionMap = request
.ProjectReferencesWithVersions
.ToDictionary(msbuildItem => msbuildItem.Identity,
msbuildItem => msbuildItem.GetProperty("ProjectVersion"), PathUtility.GetStringComparerBasedOnOS());
}
var aliases = new Dictionary<string, string>();
foreach (var tfm in assetsFile.PackageSpec.TargetFrameworks)
{
aliases[tfm.TargetAlias] = tfm.FrameworkName.GetShortFolderName();
}
var nuGetFrameworkComparer = NuGetFrameworkFullComparer.Instance;
var frameworksWithSuppressedDependencies = new HashSet<NuGetFramework>(nuGetFrameworkComparer);
if (request.FrameworksWithSuppressedDependencies != null && request.FrameworksWithSuppressedDependencies.Any())
{
frameworksWithSuppressedDependencies =
new HashSet<NuGetFramework>(request.FrameworksWithSuppressedDependencies
.Select(t =>
{
if (aliases.TryGetValue(t.Identity, out string translated))
{
return NuGetFramework.Parse(translated);
}
else
{
return NuGetFramework.Parse(t.Identity);
}
}).ToList(), nuGetFrameworkComparer);
}
PopulateProjectAndPackageReferences(builder,
assetsFile,
projectRefToVersionMap,
frameworksWithSuppressedDependencies);
PopulateFrameworkAssemblyReferences(builder, request);
PopulateFrameworkReferences(builder, assetsFile);
return builder;
}
private LicenseMetadata BuildLicenseMetadata(IPackTaskRequest<IMSBuildItem> request)
{
var hasLicenseExpression = !string.IsNullOrEmpty(request.PackageLicenseExpression);
var hasLicenseFile = !string.IsNullOrEmpty(request.PackageLicenseFile);
if (hasLicenseExpression || hasLicenseFile)
{
if (!string.IsNullOrEmpty(request.LicenseUrl))
{
throw new PackagingException(NuGetLogCode.NU5035, string.Format(
CultureInfo.CurrentCulture,
Strings.NuGetLicenses_LicenseUrlCannotBeUsedInConjuctionWithLicense));
}
if (hasLicenseExpression && hasLicenseFile)
{
throw new PackagingException(NuGetLogCode.NU5033, string.Format(
CultureInfo.CurrentCulture,
Strings.InvalidLicenseCombination,
request.PackageLicenseExpression));
}
var version = GetLicenseExpressionVersion(request);
if (hasLicenseExpression)
{
if (version.CompareTo(LicenseMetadata.CurrentVersion) <= 0)
{
try
{
var expression = NuGetLicenseExpression.Parse(request.PackageLicenseExpression);
return new LicenseMetadata(
type: LicenseType.Expression,
license: request.PackageLicenseExpression,
expression: expression,
warningsAndErrors: null,
version: version);
}
catch (NuGetLicenseExpressionParsingException e)
{
throw new PackagingException(NuGetLogCode.NU5032, string.Format(
CultureInfo.CurrentCulture,
Strings.InvalidLicenseExpression,
request.PackageLicenseExpression, e.Message),
e);
}
}
else
{
throw new PackagingException(NuGetLogCode.NU5034, string.Format(
CultureInfo.CurrentCulture,
Strings.InvalidLicenseExppressionVersion_VersionTooHigh,
request.PackageLicenseExpressionVersion,
LicenseMetadata.CurrentVersion));
}
}
if (hasLicenseFile)
{
return new LicenseMetadata(
type: LicenseType.File,
license: request.PackageLicenseFile,
expression: null,
warningsAndErrors: null,
version: version);
}
}
return null;
}
private static Version GetLicenseExpressionVersion(IPackTaskRequest<IMSBuildItem> request)
{
Version version;
if (string.IsNullOrEmpty(request.PackageLicenseExpressionVersion))
{
version = LicenseMetadata.EmptyVersion;
}
else
{
if (!Version.TryParse(request.PackageLicenseExpressionVersion, out version))
{
throw new PackagingException(NuGetLogCode.NU5034, string.Format(
CultureInfo.CurrentCulture,
Strings.InvalidLicenseExpressionVersion,
request.PackageLicenseExpressionVersion));
}
}
return version;
}
private LockFile GetAssetsFile(IPackTaskRequest<IMSBuildItem> request)
{
if (request.PackItem == null)
{
throw new PackagingException(NuGetLogCode.NU5028, Strings.NoPackItemProvided);
}
string assetsFilePath = Path.Combine(request.RestoreOutputPath, LockFileFormat.AssetsFileName);
if (!File.Exists(assetsFilePath))
{
throw new InvalidOperationException(string.Format(
CultureInfo.CurrentCulture,
Strings.AssetsFileNotFound,
assetsFilePath));
}
// The assets file is necessary for project and package references. Pack should not do any traversal,
// so we leave that work up to restore (which produces the assets file).
var lockFileFormat = new LockFileFormat();
return lockFileFormat.Read(assetsFilePath);
}
private void PopulateFrameworkAssemblyReferences(PackageBuilder builder, IPackTaskRequest<IMSBuildItem> request)
{
// First add all the assembly references which are not specific to a certain TFM.
var tfmSpecificRefs = new Dictionary<string, IList<string>>(StringComparer.OrdinalIgnoreCase);
// Then add the TFM specific framework assembly references, and ignore any which have already been added above.
foreach (var tfmRef in request.FrameworkAssemblyReferences)
{
var targetFramework = tfmRef.GetProperty("TargetFramework");
if (tfmSpecificRefs.ContainsKey(tfmRef.Identity))
{
tfmSpecificRefs[tfmRef.Identity].Add(targetFramework);
}
else
{
tfmSpecificRefs.Add(tfmRef.Identity, new List<string>() { targetFramework });
}
}
builder.FrameworkReferences.AddRange(
tfmSpecificRefs.Select(
t => new FrameworkAssemblyReference(
t.Key, t.Value.Select(
k => NuGetFramework.Parse(k))
)));
}
private void PopulateFrameworkReferences(PackageBuilder builder, LockFile assetsFile)
{
var tfmSpecificRefs = new Dictionary<string, ISet<string>>();
bool hasAnyRefs = false;
foreach (var framework in assetsFile.PackageSpec.TargetFrameworks)
{
var frameworkShortFolderName = framework.FrameworkName.GetShortFolderName();
tfmSpecificRefs.Add(frameworkShortFolderName, new HashSet<string>(ComparisonUtility.FrameworkReferenceNameComparer));
foreach (var frameworkRef in framework.FrameworkReferences.Where(e => e.PrivateAssets != FrameworkDependencyFlags.All))
{
var frameworkRefNames = tfmSpecificRefs[frameworkShortFolderName];
frameworkRefNames.Add(frameworkRef.Name);
hasAnyRefs = true;
}
}
if (hasAnyRefs)
{
builder.FrameworkReferenceGroups.AddRange(
tfmSpecificRefs.Select(e =>
new FrameworkReferenceGroup(
NuGetFramework.Parse(e.Key),
e.Value.Select(fr => new FrameworkReference(fr)))));
}
}
public PackCommandRunner GetPackCommandRunner(
IPackTaskRequest<IMSBuildItem> request,
PackArgs packArgs,
PackageBuilder packageBuilder)
{
var runner = new PackCommandRunner(
packArgs,
MSBuildProjectFactory.ProjectCreator,
packageBuilder);
runner.GenerateNugetPackage = request.ContinuePackingAfterGeneratingNuspec;
return runner;
}
public bool BuildPackage(PackCommandRunner runner)
{
return runner.RunPackageBuild();
}
private IEnumerable<OutputLibFile> InitLibFiles(IMSBuildItem[] libFiles, IDictionary<string, string> aliases)
{
var assemblies = new List<OutputLibFile>();
if (libFiles == null)
{
return assemblies;
}
foreach (var assembly in libFiles)
{
var finalOutputPath = assembly.GetProperty("FinalOutputPath");
// Fallback to using Identity if FinalOutputPath is not set.
// See bug https://github.com/NuGet/Home/issues/5408
if (string.IsNullOrEmpty(finalOutputPath))
{
finalOutputPath = assembly.GetProperty(IdentityProperty);
}
var targetPath = assembly.GetProperty("TargetPath");
var targetFramework = assembly.GetProperty("TargetFramework");
if (!File.Exists(finalOutputPath))
{
throw new PackagingException(NuGetLogCode.NU5026, string.Format(CultureInfo.CurrentCulture, Strings.Error_FileNotFound, finalOutputPath));
}
string translated = null;
var succeeded = aliases.TryGetValue(targetFramework, out translated);
if (succeeded)
{
targetFramework = translated;
}
// If target path is not set, default it to the file name. Only satellite DLLs have a special target path
// where culture is part of the target path. This condition holds true for files like runtimeconfig.json file
// in netcore projects.
if (targetPath == null)
{
targetPath = Path.GetFileName(finalOutputPath);
}
if (string.IsNullOrEmpty(targetFramework) || NuGetFramework.Parse(targetFramework).IsSpecificFramework == false)
{
throw new PackagingException(NuGetLogCode.NU5027, string.Format(CultureInfo.CurrentCulture, Strings.InvalidTargetFramework, finalOutputPath));
}
assemblies.Add(new OutputLibFile()
{
FinalOutputPath = finalOutputPath,
TargetPath = targetPath,
TargetFramework = targetFramework
});
}
return assemblies;
}
private ISet<NuGetFramework> ParseFrameworks(IPackTaskRequest<IMSBuildItem> request, IDictionary<string, string> aliases)
{
var nugetFrameworks = new HashSet<NuGetFramework>();
if (request.TargetFrameworks != null)
{
nugetFrameworks = new HashSet<NuGetFramework>(request.TargetFrameworks.Select(targetFramework =>
{
string translated = null;
var succeeded = aliases.TryGetValue(targetFramework, out translated);
if (succeeded)
{
targetFramework = translated;
}
return NuGetFramework.Parse(targetFramework);
}));
}
return nugetFrameworks;
}
private ICollection<PackageType> ParsePackageTypes(IPackTaskRequest<IMSBuildItem> request)
{
var listOfPackageTypes = new List<PackageType>();
if (request.PackageTypes != null)
{
foreach (var packageType in request.PackageTypes)
{
var packageTypeSplitInPart = packageType.Split(new char[] { ',' });
var packageTypeName = packageTypeSplitInPart[0].Trim();
var version = PackageType.EmptyVersion;
if (packageTypeSplitInPart.Length > 1)
{
var versionString = packageTypeSplitInPart[1];
_ = Version.TryParse(versionString, out version);
}
listOfPackageTypes.Add(new PackageType(packageTypeName, version));
}
}
return listOfPackageTypes;
}
private void InitCurrentDirectoryAndFileName(IPackTaskRequest<IMSBuildItem> request, PackArgs packArgs)
{
if (request.PackItem == null)
{
throw new PackagingException(NuGetLogCode.NU5028, Strings.NoPackItemProvided);
}
packArgs.CurrentDirectory = Path.Combine(
request.PackItem.GetProperty("RootDir"),
request.PackItem.GetProperty("Directory")).TrimEnd(Path.DirectorySeparatorChar);
packArgs.Arguments = new string[]
{
!string.IsNullOrEmpty(request.NuspecFile)
? request.NuspecFile
: string.Concat(request.PackItem.GetProperty("FileName"), request.PackItem.GetProperty("Extension"))
};
packArgs.Path = !string.IsNullOrEmpty(request.NuspecFile)
? request.NuspecFile
: request.PackItem.GetProperty("FullPath");
packArgs.Exclude = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
}
private void InitNuspecOutputPath(IPackTaskRequest<IMSBuildItem> request, PackArgs packArgs)
{
if (Path.IsPathRooted(request.NuspecOutputPath))
{
packArgs.PackTargetArgs.NuspecOutputPath = request.NuspecOutputPath;
}
else
{
packArgs.PackTargetArgs.NuspecOutputPath = Path.Combine(
packArgs.CurrentDirectory,
request.NuspecOutputPath);
}
}
private Dictionary<string, IEnumerable<ContentMetadata>> ProcessContentToIncludeInPackage(
IPackTaskRequest<IMSBuildItem> request,
PackArgs packArgs)
{
// This maps from source path on disk to target path inside the nupkg.
var fileModel = new Dictionary<string, IEnumerable<ContentMetadata>>();
if (request.PackageFiles != null)
{
var excludeFiles = CalculateFilesToExcludeInPack(request);
foreach (var packageFile in request.PackageFiles)
{
var sourcePath = GetSourcePath(packageFile);
if (excludeFiles.Contains(sourcePath))
{
continue;
}
var totalContentMetadata = GetContentMetadata(packageFile, sourcePath, packArgs, request.ContentTargetFolders);
if (fileModel.ContainsKey(sourcePath))
{
var existingContentMetadata = fileModel[sourcePath];
fileModel[sourcePath] = existingContentMetadata.Concat(totalContentMetadata);
}
else
{
var existingContentMetadata = new List<ContentMetadata>();
existingContentMetadata.AddRange(totalContentMetadata);
fileModel.Add(sourcePath, existingContentMetadata);
}
}
}
return fileModel;
}
// The targetpaths returned from this function contain the directory in the nuget package where the file would go to. The filename is added later on to the target path.
// whether or not the filename is added later on is dependent upon the fact that does the targetpath resolved here ends with a directory separator char or not.
private IEnumerable<ContentMetadata> GetContentMetadata(IMSBuildItem packageFile, string sourcePath,
PackArgs packArgs, string[] contentTargetFolders)
{
var targetPaths = contentTargetFolders
.Select(PathUtility.EnsureTrailingSlash)
.ToList();
var isPackagePathSpecified = packageFile.Properties.Contains("PackagePath");
// if user specified a PackagePath, then use that. Look for any ** which are indicated by the RecrusiveDir metadata in msbuild.
if (isPackagePathSpecified)
{
// The rule here is that if the PackagePath is an empty string, then we add the file to the root of the package.
// Instead if it is a ';' delimited string, then the user needs to specify a '\' to indicate that the file should go to the root of the package.
var packagePathString = packageFile.GetProperty("PackagePath");
targetPaths = packagePathString == null
? new string[] { string.Empty }.ToList()
: MSBuildStringUtility.Split(packagePathString)
.Distinct()
.ToList();
var recursiveDir = packageFile.GetProperty("RecursiveDir");
// The below NuGetRecursiveDir workaround needs to be done due to msbuild bug https://github.com/Microsoft/msbuild/issues/3121
recursiveDir = string.IsNullOrEmpty(recursiveDir) ? packageFile.GetProperty("NuGetRecursiveDir") : recursiveDir;
if (!string.IsNullOrEmpty(recursiveDir))
{
var newTargetPaths = new List<string>();
var fileName = Path.GetFileName(sourcePath);
foreach (var targetPath in targetPaths)
{
newTargetPaths.Add(PathUtility.GetStringComparerBasedOnOS().
Compare(Path.GetExtension(fileName),
Path.GetExtension(targetPath)) == 0
&& !string.IsNullOrEmpty(Path.GetExtension(fileName))
? targetPath
: Path.Combine(targetPath, recursiveDir));
}
targetPaths = newTargetPaths;
}
}
var buildActionString = packageFile.GetProperty("BuildAction");
var buildAction = BuildAction.Parse(string.IsNullOrEmpty(buildActionString) ? "None" : buildActionString);
// TODO: Do the work to get the right language of the project, tracked via https://github.com/NuGet/Home/issues/4100
var language = buildAction.Equals(BuildAction.Compile) ? "cs" : "any";
var setOfTargetPaths = new HashSet<string>(targetPaths, PathUtility.GetStringComparerBasedOnOS());
// If package path wasn't specified, then we expand the "contentFiles" value we
// got from ContentTargetFolders and expand it to contentFiles/any/<TFM>/
if (!isPackagePathSpecified)
{
if (setOfTargetPaths.Remove("contentFiles" + Path.DirectorySeparatorChar)
|| setOfTargetPaths.Remove("contentFiles"))
{
foreach (var framework in packArgs.PackTargetArgs.TargetFrameworks)
{
setOfTargetPaths.Add(PathUtility.EnsureTrailingSlash(
Path.Combine("contentFiles", language, framework.GetShortFolderName()
)));
}
}
}
// this if condition means there is no package path provided, file is within the project directory
// and the target path should preserve this relative directory structure.
// This case would be something like :
// <Content Include= "folderA\folderB\abc.txt">
// Since the package path wasn't specified, we will add this to the package paths obtained via ContentTargetFolders and preserve
// relative directory structure
if (!isPackagePathSpecified &&
sourcePath.StartsWith(packArgs.CurrentDirectory, StringComparison.CurrentCultureIgnoreCase) &&
!Path.GetFileName(sourcePath)
.Equals(packageFile.GetProperty(IdentityProperty), StringComparison.CurrentCultureIgnoreCase))
{
var newTargetPaths = new List<string>();
var identity = packageFile.GetProperty(IdentityProperty);
// Identity can be a rooted absolute path too, in which case find the path relative to the current directory
if (Path.IsPathRooted(identity))
{
identity = PathUtility.GetRelativePath(PathUtility.EnsureTrailingSlash(packArgs.CurrentDirectory), identity);
identity = Path.GetDirectoryName(identity);
}
// If identity is not a rooted path, then it is a relative path to the project directory
else if (identity.EndsWith(Path.GetFileName(sourcePath), StringComparison.CurrentCultureIgnoreCase))
{
identity = Path.GetDirectoryName(identity);
}
foreach (var targetPath in setOfTargetPaths)
{
var newTargetPath = Path.Combine(targetPath, identity);
// We need to do this because evaluated identity in the above line of code can be an empty string
// in the case when the original identity string was the absolute path to a file in project directory, and is in
// the same directory as the csproj file.
newTargetPath = PathUtility.EnsureTrailingSlash(newTargetPath);
newTargetPaths.Add(newTargetPath);
}
setOfTargetPaths = new HashSet<string>(newTargetPaths, PathUtility.GetStringComparerBasedOnOS());
}
// we take the final set of evaluated target paths and append the file name to it if not
// already done. we check whether the extension of the target path is the same as the extension
// of the source path and add the filename accordingly.
var totalSetOfTargetPaths = new List<string>();
foreach (var targetPath in setOfTargetPaths)
{
var currentPath = targetPath;
var fileName = Path.GetFileName(sourcePath);
if (string.IsNullOrEmpty(Path.GetExtension(fileName)) ||
!Path.GetExtension(fileName)
.Equals(Path.GetExtension(targetPath), StringComparison.OrdinalIgnoreCase))
{
currentPath = Path.Combine(targetPath, fileName);
}
totalSetOfTargetPaths.Add(currentPath);
}
return totalSetOfTargetPaths.Select(target => new ContentMetadata()
{
BuildAction = buildAction.Value,
Source = sourcePath,
Target = target,
CopyToOutput = packageFile.GetProperty("PackageCopyToOutput"),
Flatten = packageFile.GetProperty("PackageFlatten")
});
}
private string GetSourcePath(IMSBuildItem packageFile)
{
var sourcePath = packageFile.GetProperty("FullPath");
if (packageFile.Properties.Contains("MSBuildSourceProjectFile"))
{
var sourceProjectFile = packageFile.GetProperty("MSBuildSourceProjectFile");
var identity = packageFile.GetProperty(IdentityProperty);
sourcePath = Path.Combine(sourceProjectFile.Replace(Path.GetFileName(sourceProjectFile), string.Empty), identity);
}
return Path.GetFullPath(sourcePath);
}
private ISet<string> CalculateFilesToExcludeInPack(IPackTaskRequest<IMSBuildItem> request)
{
var excludeFiles = new HashSet<string>();
if (request.PackageFilesToExclude != null)
{
foreach (var file in request.PackageFilesToExclude)
{
var sourcePath = GetSourcePath(file);
excludeFiles.Add(sourcePath);
}
}
return excludeFiles;
}
private IDictionary<string, string> GetSourceFiles(IPackTaskRequest<IMSBuildItem> request, string currentProjectDirectory)
{
var sourceFiles = new Dictionary<string, string>();
if (request.SourceFiles != null)
{
foreach (var src in request.SourceFiles)
{
var sourcePath = GetSourcePath(src);
var sourceProjectFile = currentProjectDirectory;
if (src.Properties.Contains("MSBuildSourceProjectFile"))
{
sourceProjectFile = src.GetProperty("MSBuildSourceProjectFile");
sourceProjectFile = Path.GetDirectoryName(sourceProjectFile);
}
sourceFiles[sourcePath] = sourceProjectFile;
}
}
return sourceFiles;
}
private void PopulateProjectAndPackageReferences(PackageBuilder packageBuilder, LockFile assetsFile,
IDictionary<string, string> projectRefToVersionMap,
ISet<NuGetFramework> frameworksWithSuppressedDependencies)
{
var dependenciesByFramework = new Dictionary<NuGetFramework, HashSet<LibraryDependency>>();
InitializeProjectDependencies(assetsFile, dependenciesByFramework, projectRefToVersionMap, frameworksWithSuppressedDependencies);
InitializePackageDependencies(assetsFile, dependenciesByFramework, frameworksWithSuppressedDependencies);
foreach (var pair in dependenciesByFramework)
{
PackCommandRunner.AddDependencyGroups(pair.Value, pair.Key, packageBuilder);
}
}
private static void InitializeProjectDependencies(
LockFile assetsFile,
IDictionary<NuGetFramework, HashSet<LibraryDependency>> dependenciesByFramework,
IDictionary<string, string> projectRefToVersionMap,
ISet<NuGetFramework> frameworkWithSuppressedDependencies)
{
// From the package spec, all we know is each absolute path to the project reference the the target
// framework that project reference applies to.
if (assetsFile.PackageSpec.RestoreMetadata == null)
{
return;
}
// Using the libraries section of the assets file, the library name and version for the project path.
var projectPathToLibraryIdentities = assetsFile
.Libraries
.Where(library => library.MSBuildProject != null)
.ToLookup(
library => Path.GetFullPath(Path.Combine(
Path.GetDirectoryName(assetsFile.PackageSpec.RestoreMetadata.ProjectPath),
PathUtility.GetPathWithDirectorySeparator(library.MSBuildProject))),
library => new PackageIdentity(library.Name, library.Version),
PathUtility.GetStringComparerBasedOnOS());
// Consider all of the project references, grouped by target framework.
foreach (var framework in assetsFile.PackageSpec.RestoreMetadata.TargetFrameworks)
{
var target = assetsFile.GetTarget(framework.FrameworkName, runtimeIdentifier: null);
if (target == null || frameworkWithSuppressedDependencies.Contains(framework.FrameworkName))
{
continue;
}
HashSet<LibraryDependency> dependencies;
if (!dependenciesByFramework.TryGetValue(framework.FrameworkName, out dependencies))
{
dependencies = new HashSet<LibraryDependency>();
dependenciesByFramework[framework.FrameworkName] = dependencies;
}
// For the current target framework, create a map from library identity to library model. This allows
// us to be sure we have picked the correct library (name and version) for this target framework.
var libraryIdentityToTargetLibrary = target
.Libraries
.ToLookup(library => new PackageIdentity(library.Name, library.Version));
foreach (var projectReference in framework.ProjectReferences)
{
var libraryIdentities = projectPathToLibraryIdentities[projectReference.ProjectPath];
var targetLibrary = libraryIdentities
.Select(identity => libraryIdentityToTargetLibrary[identity].FirstOrDefault())
.FirstOrDefault(library => library != null);
if (targetLibrary == null)
{
continue;
}
var versionToUse = new VersionRange(targetLibrary.Version);
// Use the project reference version obtained at build time if it exists, otherwise fallback to the one in assets file.
if (projectRefToVersionMap.TryGetValue(projectReference.ProjectPath, out var projectRefVersion))
{
versionToUse = VersionRange.Parse(projectRefVersion, allowFloating: false);
}
// TODO: Implement <TreatAsPackageReference>false</TreatAsPackageReference>
// https://github.com/NuGet/Home/issues/3891
//
// For now, assume the project reference is a package dependency.
var projectDependency = new LibraryDependency()
{
LibraryRange = new LibraryRange(
targetLibrary.Name,
versionToUse,
LibraryDependencyTarget.All),
IncludeType = projectReference.IncludeAssets & ~projectReference.ExcludeAssets,
SuppressParent = projectReference.PrivateAssets
};
PackCommandRunner.AddLibraryDependency(projectDependency, dependencies);
}
}
}
private void InitializePackageDependencies(
LockFile assetsFile,
Dictionary<NuGetFramework, HashSet<LibraryDependency>> dependenciesByFramework,
ISet<NuGetFramework> frameworkWithSuppressedDependencies)
{
var packageSpecificNoWarnProperties = new Dictionary<string, HashSet<(NuGetLogCode, NuGetFramework)>>(StringComparer.OrdinalIgnoreCase);
var frameworks = assetsFile.PackageSpec.TargetFrameworks;
// From the package spec, we know the direct package dependencies of this project.
for (var i = 0; i < frameworks.Count; i++)
{
var framework = frameworks[i];
if (frameworkWithSuppressedDependencies.Contains(framework.FrameworkName))
{
continue;
}
// First, the framework-specific dependencies
var newFrameworkDependencies = AddDependencies(framework.Dependencies, dependenciesByFramework, framework, assetsFile, packageSpecificNoWarnProperties);
framework = new TargetFrameworkInformation(framework) { Dependencies = newFrameworkDependencies };
// Next, the central transitive dependencies
foreach (var centralTDG in assetsFile.CentralTransitiveDependencyGroups)
{
if (centralTDG.FrameworkName.Equals(framework.FrameworkName.ToString(), StringComparison.OrdinalIgnoreCase))
{
AddDependencies(centralTDG.TransitiveDependencies.ToList(), dependenciesByFramework, framework, assetsFile, packageSpecificNoWarnProperties);
}
}
var dependencies = dependenciesByFramework[framework.FrameworkName];
dependencies.RemoveWhere(dependency => IsDependencyPruned(dependency, framework.PackagesToPrune));
frameworks[i] = framework;
}
if (packageSpecificNoWarnProperties.Keys.Count > 0)
{
_packageSpecificWarningProperties = PackageSpecificWarningProperties.CreatePackageSpecificWarningProperties(packageSpecificNoWarnProperties);
}
static bool IsDependencyPruned(LibraryDependency dependency, IReadOnlyDictionary<string, PrunePackageReference> packagesToPrune)
{
if (packagesToPrune?.TryGetValue(dependency.Name, out PrunePackageReference packageToPrune) == true
&& dependency.LibraryRange.VersionRange.Satisfies(packageToPrune.VersionRange.MaxVersion))
{
return true;
}
return false;
}
}
private static void AddDependencies(
IList<LibraryDependency> packageDependencies,
Dictionary<NuGetFramework, HashSet<LibraryDependency>> dependenciesByFramework,
TargetFrameworkInformation framework,
LockFile assetsFile,
Dictionary<string, HashSet<(NuGetLogCode, NuGetFramework)>> packageSpecificNoWarnProperties)
{
HashSet<LibraryDependency> dependencies;
if (!dependenciesByFramework.TryGetValue(framework.FrameworkName, out dependencies))
{
dependencies = new HashSet<LibraryDependency>();
dependenciesByFramework[framework.FrameworkName] = dependencies;
}
// Add each package dependency.
for (int i = 0; i < packageDependencies.Count; i++)
{
var updatedPackageDependency = GetUpdatedPackageDependency(packageDependencies[i], assetsFile, framework, packageSpecificNoWarnProperties, dependencies);
packageDependencies[i] = updatedPackageDependency;
}
}
private static ImmutableArray<LibraryDependency> AddDependencies(
ImmutableArray<LibraryDependency> packageDependencies,
Dictionary<NuGetFramework, HashSet<LibraryDependency>> dependenciesByFramework,
TargetFrameworkInformation framework,
LockFile assetsFile,
Dictionary<string, HashSet<(NuGetLogCode, NuGetFramework)>> packageSpecificNoWarnProperties)
{
HashSet<LibraryDependency> dependencies;
if (!dependenciesByFramework.TryGetValue(framework.FrameworkName, out dependencies))
{
dependencies = new HashSet<LibraryDependency>();
dependenciesByFramework[framework.FrameworkName] = dependencies;
}
LibraryDependency[] updatedDependencies = new LibraryDependency[packageDependencies.Length];
// Add each package dependency.
for (var i = 0; i < packageDependencies.Length; i++)
{
var updatedPackageDependency = GetUpdatedPackageDependency(packageDependencies[i], assetsFile, framework, packageSpecificNoWarnProperties, dependencies);
updatedDependencies[i] = updatedPackageDependency;
}