Debian Codegraph @

external/nuget-buildtasks/src/Microsoft.NuGet.Build.Tasks/ResolveNuGetPackageAssets.cs

raw symbols SCIP
1 // Copyright (c) .NET Foundation. All rights reserved.
2 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3
4 using System;
5 using System.Collections.Generic;
6 using System.IO;
7 using System.Linq;
8 using System.Security.Cryptography;
9 using System.Text;
10 using Microsoft.Build.Framework;
11 using Microsoft.Build.Utilities;
12 using Newtonsoft.Json.Linq;
13 using Newtonsoft.Json;
14
15 namespace Microsoft.NuGet.Build.Tasks
16 {
17 /// <summary>
18 /// Resolves the assets out of packages in the project.lock.json
19 /// </summary>
20 public sealed class ResolveNuGetPackageAssets : Task
21 {
22 internal const string NuGetPackageIdMetadata = "NuGetPackageId";
23 internal const string NuGetPackageVersionMetadata = "NuGetPackageVersion";
24 internal const string NuGetIsFrameworkReference = "NuGetIsFrameworkReference";
25 internal const string NuGetSourceType = "NuGetSourceType";
26 internal const string NuGetSourceType_Package = "Package";
27
28 internal const string ReferenceImplementationMetadata = "Implementation";
29 internal const string ReferenceImageRuntimeMetadata = "ImageRuntime";
30 internal const string ReferenceWinMDFileMetadata = "WinMDFile";
31 internal const string ReferenceWinMDFileTypeMetadata = "WinMDFileType";
32 internal const string WinMDFileTypeManaged = "Managed";
33 internal const string WinMDFileTypeNative = "Native";
34 internal const string NuGetAssetTypeCompile = "compile";
35 internal const string NuGetAssetTypeNative = "native";
36 internal const string NuGetAssetTypeRuntime = "runtime";
37 internal const string NuGetAssetTypeResource = "resource";
38
39 internal const string RuntimeIdentifiersProperty = "RuntimeIdentifiers";
40
41 private readonly List<ITaskItem> _analyzers = new List<ITaskItem>();
42 private readonly List<ITaskItem> _copyLocalItems = new List<ITaskItem>();
43 private readonly List<ITaskItem> _references = new List<ITaskItem>();
44 private readonly List<ITaskItem> _referencedPackages = new List<ITaskItem>();
45 private readonly List<ITaskItem> _contentItems = new List<ITaskItem>();
46 private readonly List<ITaskItem> _fileWrites = new List<ITaskItem>();
47
48 private readonly List<string> _packageFolders = new List<string>();
49
50 #region UnitTestSupport
51 private readonly FileExists _fileExists = new FileExists(File.Exists);
52 private readonly TryGetRuntimeVersion _tryGetRuntimeVersion = new TryGetRuntimeVersion(TryGetRuntimeVersion);
53 private readonly bool _reportExceptionsToMSBuildLogger = true;
54
55 internal ResolveNuGetPackageAssets(FileExists fileExists, TryGetRuntimeVersion tryGetRuntimeVersion)
56 : this()
57 {
58 if (fileExists != null)
59 {
60 _fileExists = fileExists;
61 }
62
63 if (tryGetRuntimeVersion != null)
64 {
65 _tryGetRuntimeVersion = tryGetRuntimeVersion;
66 }
67
68 _reportExceptionsToMSBuildLogger = false;
69 }
70
71 // For unit testing.
72 internal IEnumerable<string> GetPackageFolders()
73 {
74 return _packageFolders;
75 }
76
77 #endregion
78
79 /// <summary>
80 /// Creates a new <see cref="ResolveNuGetPackageAssets"/>.
81 /// </summary>
82 public ResolveNuGetPackageAssets()
83 {
84 Log.TaskResources = Strings.ResourceManager;
85 }
86
87 /// <summary>
88 /// The full paths to resolved analyzers.
89 /// </summary>
90 [Output]
91 public ITaskItem[] ResolvedAnalyzers
92 {
93 get { return _analyzers.ToArray(); }
94 }
95
96 /// <summary>
97 /// The full paths to resolved run-time resources.
98 /// </summary>
99 [Output]
100 public ITaskItem[] ResolvedCopyLocalItems
101 {
102 get { return _copyLocalItems.ToArray(); }
103 }
104
105 /// <summary>
106 /// The full paths to resolved build-time dependencies. Contains standard metadata for Reference items.
107 /// </summary>
108 [Output]
109 public ITaskItem[] ResolvedReferences
110 {
111 get { return _references.ToArray(); }
112 }
113
114 /// <summary>
115 /// The names of NuGet packages directly referenced by this project.
116 /// </summary>
117 [Output]
118 public ITaskItem[] ReferencedPackages
119 {
120 get { return _referencedPackages.ToArray(); }
121 }
122
123 /// <summary>
124 /// Additional content items provided from NuGet packages.
125 /// </summary>
126 [Output]
127 public ITaskItem[] ContentItems => _contentItems.ToArray();
128
129 /// <summary>
130 /// Files written to during the generation process.
131 /// </summary>
132 [Output]
133 public ITaskItem[] FileWrites => _fileWrites.ToArray();
134
135 /// <summary>
136 /// Items specifying the tokens that can be substituted into preprocessed content files. The ItemSpec of each item is
137 /// the name of the token, without the surrounding $$, and the Value metadata should specify the replacement value.
138 /// </summary>
139 public ITaskItem[] ContentPreprocessorValues
140 {
141 get; set;
142 }
143
144 /// <summary>
145 /// The base output directory where the temporary, preprocessed files should be written to.
146 /// </summary>
147 public string ContentPreprocessorOutputDirectory
148 {
149 get; set;
150 }
151
152 /// <summary>
153 /// The target monikers to use when selecting assets from packages. The first one found in the lock file is used.
154 /// </summary>
155 [Required]
156 public ITaskItem[] TargetMonikers
157 {
158 get; set;
159 }
160
161 [Required]
162 public string ProjectLockFile
163 {
164 get; set;
165 }
166
167 public string NuGetPackagesDirectory
168 {
169 get; set;
170 }
171
172 public string RuntimeIdentifier
173 {
174 get; set;
175 }
176
177 public bool AllowFallbackOnTargetSelection
178 {
179 get; set;
180 }
181
182 public string ProjectLanguage
183 {
184 get; set;
185 }
186
187 public bool IncludeFrameworkReferences
188 {
189 get; set;
190 }
191
192 /// <summary>
193 /// Performs the NuGet package resolution.
194 /// </summary>
195 public override bool Execute()
196 {
197 try
198 {
199 ExecuteCore();
200 return true;
201 }
202 catch (ExceptionFromResource e) when (_reportExceptionsToMSBuildLogger)
203 {
204 Log.LogErrorFromResources(e.ResourceName, e.MessageArgs);
205 return false;
206 }
207 catch (Exception e) when (_reportExceptionsToMSBuildLogger)
208 {
209 // Any user-visible exceptions we throw should be ExceptionFromResource, so here we should dump stacks because
210 // something went very wrong.
211 Log.LogErrorFromException(e, showStackTrace: true);
212 return false;
213 }
214 }
215
216 private void ExecuteCore()
217 {
218 if (!_fileExists(ProjectLockFile))
219 {
220 var errorMessage = IsLockFileProjectJsonBased(ProjectLockFile) ?
221 nameof(Strings.LockFileNotFoundForProjectJson) :
222 nameof(Strings.LockFileNotFoundForProjectFile);
223
224 throw new ExceptionFromResource(errorMessage, ProjectLockFile);
225 }
226
227 JObject lockFile;
228 using (var streamReader = new StreamReader(ProjectLockFile))
229 {
230 lockFile = JObject.Load(new JsonTextReader(streamReader));
231 }
232
233 PopulatePackageFolders(lockFile);
234
235 GetReferences(lockFile);
236 GetCopyLocalItems(lockFile);
237 GetAnalyzers(lockFile);
238 GetReferencedPackages(lockFile);
239 ProduceContentAssets(lockFile);
240 }
241
242 private void PopulatePackageFolders(JObject lockFile)
243 {
244 // If we explicitly were given a path, let's use that
245 if (!string.IsNullOrEmpty(NuGetPackagesDirectory))
246 {
247 _packageFolders.Add(NuGetPackagesDirectory);
248 }
249
250 // Newer versions of NuGet can now specify the final list of locations in the lock file
251 var packageFolders = lockFile["packageFolders"] as JObject;
252
253 if (packageFolders != null)
254 {
255 foreach (var packageFolder in packageFolders.Properties())
256 {
257 _packageFolders.Add(packageFolder.Name);
258 }
259 }
260
261 // If we didn't have any folders, let's fall back to the environment variable or user profile
262 if (_packageFolders.Count == 0)
263 {
264 string packagesFolder = Environment.GetEnvironmentVariable("NUGET_PACKAGES");
265
266 if (!string.IsNullOrEmpty(packagesFolder))
267 {
268 _packageFolders.Add(packagesFolder);
269 }
270 else
271 {
272 _packageFolders.Add(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".nuget", "packages"));
273 }
274 }
275 }
276
277 private void GetReferences(JObject lockFile)
278 {
279 var target = GetTargetOrAttemptFallback(lockFile, needsRuntimeIdentifier: false);
280 var frameworkReferences = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
281 var fileNamesOfRegularReferences = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
282
283 foreach (var package in GetPackagesFromTarget(lockFile, target))
284 {
285 foreach (var referenceItem in CreateItems(package, NuGetAssetTypeCompile, includePdbs: false))
286 {
287 _references.Add(referenceItem);
288
289 fileNamesOfRegularReferences.Add(Path.GetFileNameWithoutExtension(referenceItem.ItemSpec));
290 }
291
292 if (IncludeFrameworkReferences)
293 {
294 var frameworkAssembliesArray = package.TargetObject["frameworkAssemblies"] as JArray;
295 if (frameworkAssembliesArray != null)
296 {
297 foreach (var frameworkAssembly in frameworkAssembliesArray.OfType<JToken>())
298 {
299 frameworkReferences.Add((string)frameworkAssembly);
300 }
301 }
302 }
303 }
304
305 foreach (var frameworkReference in frameworkReferences.Except(fileNamesOfRegularReferences, StringComparer.OrdinalIgnoreCase))
306 {
307 var item = new TaskItem(frameworkReference);
308 item.SetMetadata(NuGetIsFrameworkReference, "true");
309 item.SetMetadata(NuGetSourceType, NuGetSourceType_Package);
310 _references.Add(item);
311 }
312 }
313
314 private void GetCopyLocalItems(JObject lockFile)
315 {
316 // If we have no runtime identifier, we're not copying implementations
317 if (string.IsNullOrEmpty(RuntimeIdentifier))
318 {
319 return;
320 }
321
322 // We'll use as a fallback just the target moniker if the user didn't have the right runtime identifier in their lock file.
323 var target = GetTargetOrAttemptFallback(lockFile, needsRuntimeIdentifier: true);
324
325 HashSet<string> candidateNativeImplementations = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
326 List<ITaskItem> runtimeWinMDItems = new List<ITaskItem>();
327
328 foreach (var package in GetPackagesFromTarget(lockFile, target))
329 {
330 foreach (var nativeItem in CreateItems(package, NuGetAssetTypeNative))
331 {
332 if (Path.GetExtension(nativeItem.ItemSpec).Equals(".dll", StringComparison.OrdinalIgnoreCase))
333 {
334 candidateNativeImplementations.Add(Path.GetFileNameWithoutExtension(nativeItem.ItemSpec));
335 }
336
337 _copyLocalItems.Add(nativeItem);
338 }
339
340 foreach (var runtimeItem in CreateItems(package, NuGetAssetTypeRuntime))
341 {
342 if (Path.GetExtension(runtimeItem.ItemSpec).Equals(".winmd", StringComparison.OrdinalIgnoreCase))
343 {
344 runtimeWinMDItems.Add(runtimeItem);
345 }
346
347 _copyLocalItems.Add(runtimeItem);
348 }
349
350 foreach (var resourceItem in CreateItems(package, NuGetAssetTypeResource))
351 {
352 _copyLocalItems.Add(resourceItem);
353 }
354 }
355
356 SetWinMDMetadata(runtimeWinMDItems, candidateNativeImplementations);
357 }
358
359 private void GetAnalyzers(JObject lockFile)
360 {
361 // For analyzers, analyzers could be provided in runtime implementation packages. This might be reasonable -- imagine a gatekeeper
362 // scenario where somebody has a library but on .NET Native might have some specific restrictions that need to be enforced.
363 var target = GetTargetOrAttemptFallback(lockFile, needsRuntimeIdentifier: !string.IsNullOrEmpty(RuntimeIdentifier));
364
365 foreach (var package in GetPackagesFromTarget(lockFile, target))
366 {
367 var files = package.LibraryObject["files"];
368
369 if (files != null)
370 {
371 foreach (var file in files.Children()
372 .Select(x => x.ToString())
373 .Where(x => x.StartsWith("analyzers")))
374 {
375 if (Path.GetExtension(file).Equals(".dll", StringComparison.OrdinalIgnoreCase))
376 {
377 string path;
378 if (TryGetFile(package.Id, package.Version, package.RelativePackagePath, file, out path))
379 {
380 var analyzer = new TaskItem(path);
381
382 analyzer.SetMetadata(NuGetPackageIdMetadata, package.Id);
383 analyzer.SetMetadata(NuGetPackageVersionMetadata, package.Version);
384
385 _analyzers.Add(analyzer);
386 }
387 }
388 }
389 }
390 }
391 }
392
393 private void SetWinMDMetadata(IEnumerable<ITaskItem> runtimeWinMDs, ICollection<string> candidateImplementations)
394 {
395 foreach (var winMD in runtimeWinMDs.Where(w => _fileExists(w.ItemSpec)))
396 {
397 string imageRuntimeVersion = _tryGetRuntimeVersion(winMD.ItemSpec);
398
399 if (String.IsNullOrEmpty(imageRuntimeVersion))
400 continue;
401
402 // RAR sets ImageRuntime for everything but the only dependencies we're aware of are
403 // for WinMDs
404 winMD.SetMetadata(ReferenceImageRuntimeMetadata, imageRuntimeVersion);
405
406 bool isWinMD, isManaged;
407 TryParseRuntimeVersion(imageRuntimeVersion, out isWinMD, out isManaged);
408
409 if (isWinMD)
410 {
411 winMD.SetMetadata(ReferenceWinMDFileMetadata, "true");
412
413 if (isManaged)
414 {
415 winMD.SetMetadata(ReferenceWinMDFileTypeMetadata, WinMDFileTypeManaged);
416 }
417 else
418 {
419 winMD.SetMetadata(ReferenceWinMDFileTypeMetadata, WinMDFileTypeNative);
420
421 // Normally RAR will expect the native DLL to be next to the WinMD, but that doesn't
422 // work well for nuget packages since compile time assets cannot be architecture specific.
423 // We also explicitly set all compile time assets to not copy local so we need to
424 // make sure that this metadata is set on the runtime asset.
425
426 // Examine all runtime assets that are native winmds and add Implementation metadata
427 // We intentionally permit this to cross package boundaries to support cases where
428 // folks want to split their architecture specific implementations into runtime
429 // specific packages.
430
431 // Sample layout
432 // lib\netcore50\Contoso.Controls.winmd
433 // lib\netcore50\Contoso.Controls.xml
434 // runtimes\win10-arm\native\Contoso.Controls.dll
435 // runtimes\win10-x64\native\Contoso.Controls.dll
436 // runtimes\win10-x86\native\Contoso.Controls.dll
437
438 string fileName = Path.GetFileNameWithoutExtension(winMD.ItemSpec);
439
440 // determine if we have a Native WinMD that could be satisfied by this native dll.
441 if (candidateImplementations.Contains(fileName))
442 {
443 winMD.SetMetadata(ReferenceImplementationMetadata, fileName + ".dll");
444 }
445 }
446 }
447 }
448 }
449
450 private bool TryGetFile(string packageName, string packageVersion, string packageRelativePath, string file, out string path)
451 {
452 if (IsFileValid(file, "C#", "VB"))
453 {
454 path = GetPath(packageName, packageVersion, packageRelativePath, file);
455 return true;
456 }
457 else if (IsFileValid(file, "VB", "C#"))
458 {
459 path = GetPath(packageName, packageVersion, packageRelativePath, file);
460 return true;
461 }
462
463 path = null;
464 return false;
465 }
466
467 private bool IsFileValid(string file, string expectedLanguage, string unExpectedLanguage)
468 {
469 var expectedProjectLanguage = expectedLanguage;
470 expectedLanguage = expectedLanguage == "C#" ? "cs" : expectedLanguage;
471 unExpectedLanguage = unExpectedLanguage == "C#" ? "cs" : unExpectedLanguage;
472
473 return (ProjectLanguage.Equals(expectedProjectLanguage, StringComparison.OrdinalIgnoreCase)) &&
474 (file.Split('/').Any(x => x.Equals(ProjectLanguage, StringComparison.OrdinalIgnoreCase)) ||
475 !file.Split('/').Any(x => x.Equals(unExpectedLanguage, StringComparison.OrdinalIgnoreCase)));
476 }
477
478 private string GetPath(string packageName, string packageVersion, string packageRelativePath, string file)
479 {
480 return Path.Combine(GetNuGetPackagePath(packageName, packageVersion, packageRelativePath), file.Replace('/', Path.DirectorySeparatorChar));
481 }
482
483 /// <summary>
484 /// Produces a string hash of the key/values in the dictionary. This hash is used to put all the
485 /// preprocessed files into a folder with the name so we know to regenerate when any of the
486 /// inputs change.
487 /// </summary>
488 private string BuildPreprocessedContentHash(IReadOnlyDictionary<string, string> values)
489 {
490 using (var stream = new MemoryStream())
491 {
492 using (var streamWriter = new StreamWriter(stream, Encoding.UTF8, bufferSize: 4096, leaveOpen: true))
493 {
494 foreach (var pair in values.OrderBy(v => v.Key))
495 {
496 streamWriter.Write(pair.Key);
497 streamWriter.Write('\0');
498 streamWriter.Write(pair.Value);
499 streamWriter.Write('\0');
500 }
501 }
502
503 stream.Position = 0;
504
505 return SHA1.Create().ComputeHash(stream).Aggregate("", (s, b) => s + b.ToString("x2"));
506 }
507 }
508
509 private void ProduceContentAssets(JObject lockFile)
510 {
511 string valueSpecificPreprocessedOutputDirectory = null;
512 var preprocessorValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
513
514 // If a preprocessor directory isn't set, then we won't have a place to generate.
515 if (!string.IsNullOrEmpty(ContentPreprocessorOutputDirectory))
516 {
517 // Assemble the preprocessor values up-front
518 var duplicatedPreprocessorKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
519 foreach (var preprocessorValueItem in ContentPreprocessorValues ?? Enumerable.Empty<ITaskItem>())
520 {
521 if (preprocessorValues.ContainsKey(preprocessorValueItem.ItemSpec))
522 {
523 duplicatedPreprocessorKeys.Add(preprocessorValueItem.ItemSpec);
524 }
525
526 preprocessorValues[preprocessorValueItem.ItemSpec] = preprocessorValueItem.GetMetadata("Value");
527 }
528
529 foreach (var duplicatedPreprocessorKey in duplicatedPreprocessorKeys)
530 {
531 Log.LogWarningFromResources(nameof(Strings.DuplicatePreprocessorToken), duplicatedPreprocessorKey, preprocessorValues[duplicatedPreprocessorKey]);
532 }
533
534 valueSpecificPreprocessedOutputDirectory = Path.Combine(ContentPreprocessorOutputDirectory, BuildPreprocessedContentHash(preprocessorValues));
535 }
536
537 // For shared content, it does not depend upon the RID so we should ignore it
538 var target = GetTargetOrAttemptFallback(lockFile, needsRuntimeIdentifier: false);
539
540 foreach (var package in GetPackagesFromTarget(lockFile, target))
541 {
542 var contentFiles = package.TargetObject["contentFiles"] as JObject;
543 if (contentFiles != null)
544 {
545 // Is there an asset with our exact language? If so, we use that. Otherwise we'll simply collect "any" assets.
546 string codeLanguageToSelect;
547
548 if (string.IsNullOrEmpty(ProjectLanguage))
549 {
550 codeLanguageToSelect = "any";
551 }
552 else
553 {
554 string nuGetLanguageName = GetNuGetLanguageName(ProjectLanguage);
555 if (contentFiles.Properties().Any(a => (string)a.Value["codeLanguage"] == nuGetLanguageName))
556 {
557 codeLanguageToSelect = nuGetLanguageName;
558 }
559 else
560 {
561 codeLanguageToSelect = "any";
562 }
563 }
564
565 foreach (var contentFile in contentFiles.Properties())
566 {
567 // Ignore magic _._ placeholder files. We couldn't ignore them during the project language
568 // selection, since you could imagine somebody might have a package that puts assets under
569 // "any" but then uses _._ to opt some languages out of it
570 if (Path.GetFileName(contentFile.Name) != "_._")
571 {
572 if ((string)contentFile.Value["codeLanguage"] == codeLanguageToSelect)
573 {
574 ProduceContentAsset(package, contentFile, preprocessorValues, valueSpecificPreprocessedOutputDirectory);
575 }
576 }
577 }
578 }
579 }
580 }
581
582 private static string GetNuGetLanguageName(string projectLanguage)
583 {
584 switch (projectLanguage)
585 {
586 case "C#": return "cs";
587 case "F#": return "fs";
588 default: return projectLanguage.ToLowerInvariant();
589 }
590 }
591
592 /// <summary>
593 /// Produces the asset for a single shared asset. All applicablility checks have already been completed.
594 /// </summary>
595 private void ProduceContentAsset(NuGetPackageObject package, JProperty sharedAsset, IReadOnlyDictionary<string, string> preprocessorValues, string preprocessedOutputDirectory)
596 {
597 string pathToFinalAsset = package.GetFullPathToFile(sharedAsset.Name);
598
599 if (sharedAsset.Value["ppOutputPath"] != null)
600 {
601 if (preprocessedOutputDirectory == null)
602 {
603 throw new ExceptionFromResource(nameof(Strings.PreprocessedDirectoryNotSet), nameof(ContentPreprocessorOutputDirectory));
604 }
605
606 // We need the preprocessed output, so let's run the preprocessor here
607 pathToFinalAsset = Path.Combine(preprocessedOutputDirectory, package.Id, package.Version, (string)sharedAsset.Value["ppOutputPath"]);
608
609 if (!File.Exists(pathToFinalAsset))
610 {
611 Directory.CreateDirectory(Path.GetDirectoryName(pathToFinalAsset));
612
613 using (var input = new StreamReader(package.GetFullPathToFile(sharedAsset.Name), detectEncodingFromByteOrderMarks: true))
614 using (var output = new StreamWriter(pathToFinalAsset, append: false, encoding: input.CurrentEncoding))
615 {
616 Preprocessor.Preprocess(input, output, preprocessorValues);
617 }
618
619 _fileWrites.Add(new TaskItem(pathToFinalAsset));
620 }
621 }
622
623 if ((bool)sharedAsset.Value["copyToOutput"])
624 {
625 string outputPath = (string)sharedAsset.Value["outputPath"] ?? (string)sharedAsset.Value["ppOutputPath"];
626
627 if (outputPath != null)
628 {
629 var item = CreateItem(package, pathToFinalAsset, targetPath: outputPath);
630 _copyLocalItems.Add(item);
631 }
632 }
633
634 string buildAction = (string)sharedAsset.Value["buildAction"];
635 if (!string.Equals(buildAction, "none", StringComparison.OrdinalIgnoreCase))
636 {
637 var item = CreateItem(package, pathToFinalAsset);
638
639 // We'll put additional metadata on the item so we can convert it back to the real item group in our targets
640 item.SetMetadata("NuGetItemType", buildAction);
641
642 // If this is XAML, the build targets expect Link metadata to construct the relative path
643 if (string.Equals(buildAction, "Page", StringComparison.OrdinalIgnoreCase))
644 {
645 item.SetMetadata("Link", Path.Combine("NuGet", package.Id, package.Version, Path.GetFileName(sharedAsset.Name)));
646 }
647
648 _contentItems.Add(item);
649 }
650 }
651
652 /// <summary>
653 /// Fetches the right target from the targets section in a lock file, or attempts to find a "best match" if allowed. The "best match" logic
654 /// is there to allow a design time build for the IDE to generally work even if something isn't quite right. Throws an exception
655 /// if either the preferred isn't there and fallbacks aren't allowed, or fallbacks are allowed but nothing at all could be found.
656 /// </summary>
657 /// <param name="lockFile">The lock file JSON.</param>
658 /// <param name="needsRuntimeIdentifier">Whether we must find targets that include the runtime identifier or one without the runtime identifier.</param>
659 private JObject GetTargetOrAttemptFallback(JObject lockFile, bool needsRuntimeIdentifier)
660 {
661 var targets = (JObject)lockFile["targets"];
662
663 foreach (var preferredTargetMoniker in TargetMonikers)
664 {
665 var preferredTargetMonikerWithOptionalRuntimeIdentifier = GetTargetMonikerWithOptionalRuntimeIdentifier(preferredTargetMoniker, needsRuntimeIdentifier);
666 var target = (JObject)targets[preferredTargetMonikerWithOptionalRuntimeIdentifier];
667
668 if (target != null)
669 {
670 return target;
671 }
672 }
673
674 // If we need a runtime identifier, let's see if we have the framework targeted. If we do,
675 // then we can give a better error message.
676 bool onlyNeedsRuntimeInProjectJson = false;
677 if (needsRuntimeIdentifier)
678 {
679 foreach (var targetMoniker in TargetMonikers)
680 {
681 var targetMonikerWithoutRuntimeIdentifier = GetTargetMonikerWithOptionalRuntimeIdentifier(targetMoniker, needsRuntimeIdentifier: false);
682 if (targets[targetMonikerWithoutRuntimeIdentifier] != null)
683 {
684 // We do have a TXM being targeted, so we just are missing the runtime
685 onlyNeedsRuntimeInProjectJson = true;
686 break;
687 }
688 }
689 }
690
691 if (onlyNeedsRuntimeInProjectJson)
692 {
693 GiveErrorForMissingRuntimeIdentifier();
694 }
695 else
696 {
697 GiveErrorForMissingFramework();
698 }
699
700 // If we're still here, that means we're allowing fallback, so let's try
701 foreach (var fallback in TargetMonikers)
702 {
703 var target = (JObject)targets[GetTargetMonikerWithOptionalRuntimeIdentifier(fallback, needsRuntimeIdentifier: false)];
704
705 if (target != null)
706 {
707 return target;
708 }
709 }
710
711 // Anything goes
712 var enumerableTargets = targets.Cast<KeyValuePair<string, JToken>>();
713 var firstTarget = (JObject)enumerableTargets.FirstOrDefault().Value;
714 if (firstTarget == null)
715 {
716 GiveErrorForNoTargets();
717 }
718
719 return firstTarget;
720 }
721
722 private void GiveErrorForNoTargets()
723 {
724 var noTargetsInLockFileErrorString = IsLockFileProjectJsonBased(ProjectLockFile) ?
725 nameof(Strings.NoTargetsInLockFileForProjectJson) :
726 nameof(Strings.NoTargetsInLockFileForProjectFile);
727
728 throw new ExceptionFromResource(noTargetsInLockFileErrorString);
729 }
730
731 private void GiveErrorForMissingRuntimeIdentifier()
732 {
733 var runtimePiece = RuntimeIdentifier;
734 var runtimesSection = $"<{RuntimeIdentifiersProperty}>{RuntimeIdentifier}</{RuntimeIdentifiersProperty}>";
735 var missingRuntimeInRuntimesErrorString = nameof(Strings.MissingRuntimeIdentifierInProjectFile);
736 var missingRuntimesErrorString = nameof(Strings.MissingRuntimeIdentifierPropertyInProjectFile);
737
738 if (IsLockFileProjectJsonBased(ProjectLockFile))
739 {
740 runtimePiece = '"' + RuntimeIdentifier + "\": { }";
741 runtimesSection = "\"runtimes\": { " + runtimePiece + " }";
742 missingRuntimeInRuntimesErrorString = nameof(Strings.MissingRuntimeInProjectJson);
743 missingRuntimesErrorString = nameof(Strings.MissingRuntimesSectionInProjectJson);
744 }
745
746 bool hasRuntimesSection = true;
747 try
748 {
749 // try reading the project.json file only of the project is project.json based
750 if (IsLockFileProjectJsonBased(ProjectLockFile))
751 {
752 using (var streamReader = new StreamReader(ProjectLockFile.Replace(".lock.json", ".json")))
753 {
754 var jsonFile = JObject.Load(new JsonTextReader(streamReader));
755 hasRuntimesSection = jsonFile["runtimes"] != null;
756 }
757 }
758 }
759 catch
760 {
761 // User has a bad file, locked file, no file at all, etc. We'll just assume they have one.
762 hasRuntimesSection = true;
763 }
764
765 if (hasRuntimesSection)
766 {
767 ThrowExceptionIfNotAllowingFallback(missingRuntimeInRuntimesErrorString, RuntimeIdentifier, runtimePiece);
768 }
769 else
770 {
771 ThrowExceptionIfNotAllowingFallback(missingRuntimesErrorString, runtimesSection);
772 }
773 }
774
775 private void GiveErrorForMissingFramework()
776 {
777 var missingFrameworkErrorString = IsLockFileProjectJsonBased(ProjectLockFile) ?
778 nameof(Strings.MissingFrameworkInProjectJson) :
779 nameof(Strings.MissingFrameworkInProjectFile);
780
781 ThrowExceptionIfNotAllowingFallback(missingFrameworkErrorString, TargetMonikers.First().ItemSpec);
782 }
783
784 private void ThrowExceptionIfNotAllowingFallback(string resourceName, params string[] messageArgs)
785 {
786 if (!AllowFallbackOnTargetSelection)
787 {
788 throw new ExceptionFromResource(resourceName, messageArgs);
789 }
790 else
791 {
792 // We are allowing fallback, so we'll still give a warning but allow us to continue
793 Log.LogWarningFromResources(resourceName, messageArgs);
794 }
795 }
796
797 private string GetTargetMonikerWithOptionalRuntimeIdentifier(ITaskItem preferredTargetMoniker, bool needsRuntimeIdentifier)
798 {
799 return needsRuntimeIdentifier ? preferredTargetMoniker.ItemSpec + "/" + RuntimeIdentifier : preferredTargetMoniker.ItemSpec;
800 }
801
802 private IEnumerable<ITaskItem> CreateItems(NuGetPackageObject package, string key, bool includePdbs = true)
803 {
804 var values = package.TargetObject[key] as JObject;
805 var items = new List<ITaskItem>();
806
807 if (values == null)
808 {
809 return items;
810 }
811
812 foreach (var file in values.Properties())
813 {
814 if (Path.GetFileName(file.Name) == "_._")
815 {
816 continue;
817 }
818
819 string targetPath = null;
820 string culture = file.Value["locale"]?.ToString();
821
822 if (culture != null)
823 {
824 targetPath = Path.Combine(culture, Path.GetFileName(file.Name));
825 }
826
827 var item = CreateItem(package, package.GetFullPathToFile(file.Name), targetPath);
828
829 item.SetMetadata("Private", "false");
830 item.SetMetadata(NuGetIsFrameworkReference, "false");
831 item.SetMetadata(NuGetSourceType, NuGetSourceType_Package);
832
833 items.Add(item);
834
835 // If there's a PDB alongside the implementation, we should copy that as well
836 if (includePdbs)
837 {
838 var pdbFileName = Path.ChangeExtension(item.ItemSpec, ".pdb");
839
840 if (_fileExists(pdbFileName))
841 {
842 var pdbItem = new TaskItem(pdbFileName);
843
844 // CopyMetadataTo also includes an OriginalItemSpec that will point to our original item, as we want
845 item.CopyMetadataTo(pdbItem);
846
847 items.Add(pdbItem);
848 }
849
850 // handle Mono mdb debug symbols
851 var mdbFileName = item.ItemSpec + ".mdb";
852
853 if (_fileExists(mdbFileName))
854 {
855 var mdbItem = new TaskItem(mdbFileName);
856
857 // CopyMetadataTo also includes an OriginalItemSpec that will point to our original item, as we want
858 item.CopyMetadataTo(mdbItem);
859
860 items.Add(mdbItem);
861 }
862 }
863 }
864
865 return items;
866 }
867
868 private static ITaskItem CreateItem(NuGetPackageObject package, string itemSpec, string targetPath = null)
869 {
870 var item = new TaskItem(itemSpec);
871
872 item.SetMetadata(NuGetPackageIdMetadata, package.Id);
873 item.SetMetadata(NuGetPackageVersionMetadata, package.Version);
874
875 if (targetPath != null)
876 {
877 item.SetMetadata("TargetPath", targetPath);
878
879 var destinationSubDirectory = Path.GetDirectoryName(targetPath);
880
881 if (!string.IsNullOrEmpty(destinationSubDirectory))
882 {
883 item.SetMetadata("DestinationSubDirectory", destinationSubDirectory + Path.DirectorySeparatorChar);
884 }
885 }
886
887 return item;
888 }
889
890 private void GetReferencedPackages(JObject lockFile)
891 {
892 var targets = (JObject)lockFile["targets"];
893
894 string targetMoniker = null;
895 foreach (var preferredTargetMoniker in TargetMonikers)
896 {
897 var preferredTargetMonikerWithOptionalRuntimeIdentifier = GetTargetMonikerWithOptionalRuntimeIdentifier(preferredTargetMoniker, needsRuntimeIdentifier: false);
898 var target = (JObject)targets[preferredTargetMonikerWithOptionalRuntimeIdentifier];
899
900 if (target != null)
901 {
902 targetMoniker = preferredTargetMonikerWithOptionalRuntimeIdentifier;
903 break;
904 }
905 }
906
907 var projectFileDependencyGroups = (JObject)lockFile["projectFileDependencyGroups"];
908 var allPackageNames = GetAllPackageNames(lockFile);
909
910 if (targetMoniker != null)
911 {
912 var targetSpecificDependencies = (JArray)projectFileDependencyGroups[targetMoniker];
913 if (targetSpecificDependencies != null)
914 {
915 AddReferencedPackages(targetSpecificDependencies, allPackageNames);
916 }
917 }
918
919 var universalDependencies = (JArray)projectFileDependencyGroups[""];
920 if (universalDependencies != null)
921 {
922 AddReferencedPackages(universalDependencies, allPackageNames);
923 }
924 }
925
926 /// <summary>
927 /// Returns the set of all the package names (not including version numbers)
928 /// in the "libraries" section of the assets/lock file. Note that this includes
929 /// only proper packages; projects are specifically excluded.
930 /// </summary>
931 private static SortedSet<string> GetAllPackageNames(JObject lockFile)
932 {
933 var allPackageNames = new SortedSet<string>(StringComparer.OrdinalIgnoreCase);
934 var libraries = (JObject)lockFile["libraries"];
935 foreach (var library in libraries)
936 {
937 var libraryObject = (JObject)library.Value;
938 string type = (string)libraryObject["type"];
939 if (type != null &&
940 type.Equals("project", StringComparison.OrdinalIgnoreCase))
941 {
942 continue;
943 }
944
945 string name, version;
946 SplitPackageName(library.Key, out name, out version);
947 allPackageNames.Add(name);
948 }
949
950 return allPackageNames;
951 }
952
953 /// <summary>
954 /// Given a set of dependencies, identities the packages and adds their names to <see cref="_referencedPackages"/>.
955 /// </summary>
956 private void AddReferencedPackages(JArray packageDependencies, SortedSet<string> allPackageNames)
957 {
958 foreach (var packageDependency in packageDependencies.Select(v => (string)v))
959 {
960 // Strip the version, if any, from the dependency.
961 int firstSpace = packageDependency.IndexOf(' ');
962 string packageName = firstSpace > -1
963 ? packageDependency.Substring(0, firstSpace)
964 : packageDependency;
965
966 if (allPackageNames.Contains(packageName))
967 {
968 _referencedPackages.Add(new TaskItem(packageName));
969 }
970 }
971 }
972
973 private string GetNuGetPackagePath(string packageId, string packageVersion, string packageRelativePath)
974 {
975 string relativePathToUse = String.IsNullOrEmpty(packageRelativePath)
976 ? Path.Combine(packageId, packageVersion)
977 : packageRelativePath.Replace('/', Path.DirectorySeparatorChar);
978
979 string hashFileName = $"{packageId.ToLowerInvariant()}.{packageVersion.ToLowerInvariant()}.nupkg.sha512";
980
981 foreach (var packagesFolder in _packageFolders)
982 {
983 string packageFullPath = Path.Combine(packagesFolder, relativePathToUse);
984
985 // The proper way to check if a package is available is to look for the hash file, since that's the last
986 // file written as a part of the restore process. If it's not there, it means something failed part way through.
987 if (_fileExists(Path.Combine(packageFullPath, hashFileName)))
988 {
989 return packageFullPath;
990 }
991 }
992
993 throw new ExceptionFromResource(nameof(Strings.PackageFolderNotFound), packageId, packageVersion, string.Join(", ", _packageFolders));
994 }
995
996 private IEnumerable<NuGetPackageObject> GetPackagesFromTarget(JObject lockFile, JObject target)
997 {
998 foreach (var package in target)
999 {
1000 string id, version;
1001 SplitPackageName(package.Key, out id, out version);
1002
1003 var libraryObject = (JObject)lockFile["libraries"][package.Key];
1004
1005 Func<string> fullPackagePathGenerator;
1006
1007 if (libraryObject == null)
1008 {
1009 var errorMessage = IsLockFileProjectJsonBased(ProjectLockFile) ?
1010 nameof(Strings.MissingPackageInTargetsForProjectJson) :
1011 nameof(Strings.MissingPackageInTargetsSectionForProjectFile);
1012
1013 throw new ExceptionFromResource(errorMessage, package.Key);
1014 }
1015
1016 // If this is a project then we need to figure out it's relative output path
1017 if ("project".Equals((string)libraryObject["type"], StringComparison.OrdinalIgnoreCase))
1018 {
1019 continue;
1020 }
1021 else
1022 {
1023 fullPackagePathGenerator = () => GetNuGetPackagePath(id, version, (string)libraryObject["path"]);
1024 }
1025
1026 yield return new NuGetPackageObject(id, version, fullPackagePathGenerator, (JObject)package.Value, libraryObject);
1027 }
1028 }
1029
1030 private static void SplitPackageName(string key, out string id, out string version)
1031 {
1032 var nameParts = key.Split('/');
1033 id = nameParts[0];
1034 version = nameParts[1];
1035 }
1036
1037 private string GetAbsolutePathFromProjectRelativePath(string path)
1038 {
1039 return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Path.GetFullPath(ProjectLockFile)), path));
1040 }
1041
1042 /// <summary>
1043 /// Parse the imageRuntimeVersion from COR header
1044 /// </summary>
1045 private void TryParseRuntimeVersion(string imageRuntimeVersion, out bool isWinMD, out bool isManaged)
1046 {
1047 if (!String.IsNullOrEmpty(imageRuntimeVersion))
1048 {
1049 isWinMD = imageRuntimeVersion.IndexOf("WindowsRuntime", StringComparison.OrdinalIgnoreCase) >= 0;
1050 isManaged = imageRuntimeVersion.IndexOf("CLR", StringComparison.OrdinalIgnoreCase) >= 0;
1051 }
1052 else
1053 {
1054 isWinMD = isManaged = false;
1055 }
1056 }
1057
1058 /// <summary>
1059 /// Given a path get the CLR runtime version of the file
1060 /// </summary>
1061 /// <param name="path">path to the file</param>
1062 /// <returns>The CLR runtime version or empty if the path does not exist.</returns>
1063 private static string TryGetRuntimeVersion(string path)
1064 {
1065 StringBuilder runtimeVersion = null;
1066 uint hresult = 0;
1067 uint actualBufferSize = 0;
1068 int bufferLength = 11; // 11 is the length of a runtime version and null terminator v2.0.50727/0
1069
1070 do
1071 {
1072 runtimeVersion = new StringBuilder(bufferLength);
1073 hresult = NativeMethods.GetFileVersion(path, runtimeVersion, bufferLength, out actualBufferSize);
1074 bufferLength = bufferLength * 2;
1075
1076 } while (hresult == NativeMethods.ERROR_INSUFFICIENT_BUFFER);
1077
1078 if (hresult == NativeMethods.S_OK && runtimeVersion != null)
1079 {
1080 return runtimeVersion.ToString();
1081 }
1082 else
1083 {
1084 return String.Empty;
1085 }
1086 }
1087
1088 private static bool IsLockFileProjectJsonBased(string lockFilePath)
1089 {
1090 return lockFilePath.EndsWith("lock.json", StringComparison.OrdinalIgnoreCase);
1091 }
1092 }
1093 }