// Gets the runtime graph specified in the path.
 // returns null if an error is hit. A valid runtime graph otherwise.
 private RuntimeGraph GetRuntimeGraph(string runtimeGraphPath)
 {
     if (File.Exists(runtimeGraphPath))
     {
         try
         {
             using (var stream = File.OpenRead(runtimeGraphPath))
             {
                 var runtimeGraph = JsonRuntimeFormat.ReadRuntimeGraph(stream);
                 return(runtimeGraph);
             }
         }
         catch (Exception e)
         {
             _logger.Log(
                 RestoreLogMessage.CreateError(
                     NuGetLogCode.NU1007,
                     string.Format(CultureInfo.CurrentCulture,
                                   Strings.Error_ProjectRuntimeJsonIsUnreadable,
                                   runtimeGraphPath,
                                   e.Message)));
         }
     }
     else
     {
         _logger.Log(
             RestoreLogMessage.CreateError(
                 NuGetLogCode.NU1007,
                 string.Format(CultureInfo.CurrentCulture,
                               Strings.Error_ProjectRuntimeJsonNotFound,
                               runtimeGraphPath)));
     }
     return(null);
 }
Example #2
0
        public RuntimeGraph GetRuntimeGraph(string runtimeJsonPath)
        {
            if (string.IsNullOrEmpty(runtimeJsonPath))
            {
                throw new ArgumentNullException(nameof(runtimeJsonPath));
            }
            if (!Path.IsPathRooted(runtimeJsonPath))
            {
                throw new BuildErrorException("Path not rooted: {0}", runtimeJsonPath);
            }

            string key = GetTaskObjectKey(runtimeJsonPath);

            RuntimeGraph result;
            object       existingRuntimeGraphTaskObject = _buildEngine.GetRegisteredTaskObject(key, RegisteredTaskObjectLifetime.AppDomain);

            if (existingRuntimeGraphTaskObject == null)
            {
                result = JsonRuntimeFormat.ReadRuntimeGraph(runtimeJsonPath);

                _buildEngine.RegisterTaskObject(key, result, RegisteredTaskObjectLifetime.AppDomain, true);
            }
            else
            {
                result = (RuntimeGraph)existingRuntimeGraphTaskObject;
            }

            return(result);
        }
Example #3
0
        protected override void ExecuteCore()
        {
            RuntimeGraph runtimeGraph = null;

            if (!string.IsNullOrEmpty(RuntimeGraph))
            {
                runtimeGraph = JsonRuntimeFormat.ReadRuntimeGraph(RuntimeGraph);
            }

            Package package = NupkgParser.CreatePackage(PackageTargetPath, runtimeGraph);
            PackageValidationLogger logger = new(Log, CompatibilitySuppressionFilePath, GenerateCompatibilitySuppressionFile);

            new CompatibleTfmValidator(NoWarn, null, RunApiCompat, EnableStrictModeForCompatibleTfms, logger).Validate(package);
            new CompatibleFrameworkInPackageValidator(NoWarn, null, EnableStrictModeForCompatibleFrameworksInPackage, logger).Validate(package);

            if (!DisablePackageBaselineValidation && !string.IsNullOrEmpty(BaselinePackageTargetPath))
            {
                Package baselinePackage = NupkgParser.CreatePackage(BaselinePackageTargetPath, runtimeGraph);
                new BaselinePackageValidator(baselinePackage, NoWarn, null, RunApiCompat, logger).Validate(package);
            }

            if (GenerateCompatibilitySuppressionFile)
            {
                logger.GenerateSuppressionsFile(CompatibilitySuppressionFilePath);
            }
        }
 private RuntimeGraph ParseRuntimeJsonString(string content)
 {
     using (var reader = new StringReader(content))
     {
         return(JsonRuntimeFormat.ReadRuntimeGraph(reader));
     }
 }
        /// <summary>
        /// Runs GenerateRuntimeGraph task specifying AdditionalRuntimeIdentifiers then asserts that the
        /// generated runtime.json has the expected additions (and no more).
        /// </summary>
        /// <param name="additionalRIDs">additional RIDs</param>
        /// <param name="expectedAdditions">entries that are expected to be added to the RuntimeGraph</param>
        /// <param name="additionalRIDParent">parent to use when adding a new RID</param>
        /// <param name="runtimeFilePrefix">a unique prefix to use for the generated </param>
        private void AssertRuntimeGraphAdditions(string[] additionalRIDs, RuntimeDescription[] expectedAdditions, string additionalRIDParent = null, [CallerMemberName] string runtimeFilePrefix = null)
        {
            string runtimeFile = Path.Combine(defaultRootPath, runtimeFilePrefix + ".runtime.json");

            GenerateRuntimeGraph task = new GenerateRuntimeGraph()
            {
                BuildEngine   = _engine,
                RuntimeGroups = DefaultRuntimeGroupItems,
                RuntimeJson   = runtimeFile,
                AdditionalRuntimeIdentifiers      = additionalRIDs,
                AdditionalRuntimeIdentifierParent = additionalRIDParent,
                UpdateRuntimeFiles = true
            };

            _log.Reset();
            task.Execute();
            _log.AssertNoErrorsOrWarnings();

            RuntimeGraph expected = RuntimeGraph.Merge(
                JsonRuntimeFormat.ReadRuntimeGraph(defaultRuntimeFile),
                new RuntimeGraph(expectedAdditions));

            RuntimeGraph actual = JsonRuntimeFormat.ReadRuntimeGraph(runtimeFile);

            // Should this assert fail, it's helpful to diff defaultRuntimeFile and runtimeFile to see the additions.
            Assert.Equal(expected, actual);
        }
Example #6
0
        public static void WritePackageSpec(PackageSpec packageSpec, JObject json)
        {
            SetValue(json, "title", packageSpec.Title);

            if (!packageSpec.IsDefaultVersion)
            {
                SetValue(json, "version", packageSpec.Version?.ToNormalizedString());
            }

            SetValue(json, "description", packageSpec.Description);
            SetArrayValue(json, "authors", packageSpec.Authors);
            SetValue(json, "copyright", packageSpec.Copyright);
            SetValue(json, "language", packageSpec.Language);
            SetArrayValue(json, "contentFiles", packageSpec.ContentFiles);
            SetDictionaryValue(json, "packInclude", packageSpec.PackInclude);
            SetPackOptions(json, packageSpec);
            SetDictionaryValues(json, "scripts", packageSpec.Scripts);

            if (packageSpec.Dependencies.Any())
            {
                SetDependencies(json, packageSpec.Dependencies);
            }

            if (packageSpec.Tools.Any())
            {
                JObject tools = new JObject();
                foreach (var tool in packageSpec.Tools)
                {
                    JObject toolObject = new JObject();
                    toolObject["version"] = tool.LibraryRange.VersionRange.ToNormalizedString();

                    if (tool.Imports.Any())
                    {
                        SetImports(toolObject, tool.Imports);
                    }
                    tools[tool.LibraryRange.Name] = toolObject;
                }

                SetValue(json, "tools", tools);
            }

            if (packageSpec.TargetFrameworks.Any())
            {
                JObject frameworks = new JObject();
                foreach (var framework in packageSpec.TargetFrameworks)
                {
                    JObject frameworkObject = new JObject();

                    SetDependencies(frameworkObject, framework.Dependencies);
                    SetImports(frameworkObject, framework.Imports);

                    frameworks[framework.FrameworkName.GetShortFolderName()] = frameworkObject;
                }

                SetValue(json, "frameworks", frameworks);
            }

            JsonRuntimeFormat.WriteRuntimeGraph(json, packageSpec.RuntimeGraph);
        }
Example #7
0
 /// <summary>
 /// Initializes static members of the <see cref="PackageUtils"/> class.
 /// </summary>
 static PackageUtils()
 {
     // the original data was taken from: https://github.com/dotnet/corefx/blob/master/pkg/Microsoft.NETCore.Platforms/runtime.json
     // the additional documentation: https://docs.microsoft.com/en-us/dotnet/core/rid-catalog
     runtimeGraph = JsonRuntimeFormat.ReadRuntimeGraph(
         typeof(PackageUtils).GetTypeInfo().Assembly
         .GetManifestResourceStream("KlusterKite.NodeManager.Launcher.Utils.Resources.runtimes.json"));
 }
Example #8
0
        public override bool Execute()
        {
            var runtimeIdentifierGraph = JsonRuntimeFormat.ReadRuntimeGraph(RuntimeIdentifierGraphPath);

            var chainContents = string.Join("\n", runtimeIdentifierGraph.ExpandRuntime(RuntimeIdentifier));

            File.WriteAllText(RuntimeIdentifierChainOutputPath, chainContents);

            return(true);
        }
Example #9
0
        protected override void ExecuteCore()
        {
            RuntimeGraph runtimeGraph = null;

            if (!string.IsNullOrEmpty(RuntimeGraph))
            {
                runtimeGraph = JsonRuntimeFormat.ReadRuntimeGraph(RuntimeGraph);
            }

            Dictionary <string, HashSet <string> > apiCompatReferences = new();

            if (ReferencePaths != null)
            {
                foreach (ITaskItem taskItem in ReferencePaths)
                {
                    string tfm = taskItem.GetMetadata("TargetFramework");
                    if (string.IsNullOrEmpty(tfm))
                    {
                        continue;
                    }

                    string referencePath = taskItem.GetMetadata("Identity");
                    if (!File.Exists(referencePath))
                    {
                        continue;
                    }

                    if (!apiCompatReferences.TryGetValue(tfm, out HashSet <string> directories))
                    {
                        directories = new();
                        apiCompatReferences.Add(tfm, directories);
                    }

                    directories.Add(referencePath);
                }
            }

            Package             package = NupkgParser.CreatePackage(PackageTargetPath, runtimeGraph);
            CompatibilityLogger logger  = new(Log, CompatibilitySuppressionFilePath, GenerateCompatibilitySuppressionFile);

            new CompatibleTfmValidator(NoWarn, null, RunApiCompat, EnableStrictModeForCompatibleTfms, logger, apiCompatReferences).Validate(package);
            new CompatibleFrameworkInPackageValidator(NoWarn, null, EnableStrictModeForCompatibleFrameworksInPackage, logger, apiCompatReferences).Validate(package);

            if (!DisablePackageBaselineValidation && !string.IsNullOrEmpty(BaselinePackageTargetPath))
            {
                Package baselinePackage = NupkgParser.CreatePackage(BaselinePackageTargetPath, runtimeGraph);
                new BaselinePackageValidator(baselinePackage, NoWarn, null, RunApiCompat, logger, apiCompatReferences).Validate(package);
            }

            if (GenerateCompatibilitySuppressionFile)
            {
                logger.GenerateSuppressionsFile(CompatibilitySuppressionFilePath);
            }
        }
Example #10
0
        public AggregateNuGetAssetResolver(string runtimeFile)
        {
            RuntimeGraph runtimeGraph = null;

            if (!String.IsNullOrEmpty(runtimeFile))
            {
                runtimeGraph = JsonRuntimeFormat.ReadRuntimeGraph(runtimeFile);
            }
            _conventions = new ManagedCodeConventions(runtimeGraph);
            _packages    = new Dictionary <string, ContentItemCollection>();
        }
Example #11
0
        public NuGetAssetResolver(string runtimeFile, IEnumerable <string> packageItems)
        {
            RuntimeGraph runtimeGraph = null;

            if (!String.IsNullOrEmpty(runtimeFile))
            {
                runtimeGraph = JsonRuntimeFormat.ReadRuntimeGraph(runtimeFile);
            }
            _conventions = new ManagedCodeConventions(runtimeGraph);

            _sourceItems = new ContentItemCollection();
            _sourceItems.Load(packageItems);
        }
Example #12
0
        private RuntimeGraph LoadRuntimeGraph(LocalPackageInfo package)
        {
            var runtimeGraphFile = Path.Combine(package.ExpandedPath, RuntimeGraph.RuntimeGraphFileName);

            if (File.Exists(runtimeGraphFile))
            {
                using (var stream = new FileStream(runtimeGraphFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    return(JsonRuntimeFormat.ReadRuntimeGraph(stream));
                }
            }
            return(null);
        }
Example #13
0
        private static RuntimeGraph LoadRuntimeGraphCore(LocalPackageInfo package)
        {
            var runtimeGraphFile = Path.Combine(package.ExpandedPath, RuntimeGraph.RuntimeGraphFileName);

            if (File.Exists(runtimeGraphFile))
            {
                using (var stream = File.OpenRead(runtimeGraphFile))
                {
                    return(JsonRuntimeFormat.ReadRuntimeGraph(stream));
                }
            }
            return(null);
        }
Example #14
0
        /// <summary>
        /// Return runtime.json from a package.
        /// </summary>
        private RuntimeGraph GetRuntimeGraph(string expandedPath)
        {
            var runtimeGraphFile = Path.Combine(expandedPath, RuntimeGraph.RuntimeGraphFileName);

            if (File.Exists(runtimeGraphFile))
            {
                using (var stream = File.OpenRead(runtimeGraphFile))
                {
                    return(JsonRuntimeFormat.ReadRuntimeGraph(stream));
                }
            }

            return(null);
        }
Example #15
0
        public override bool Execute()
        {
            if (RuntimeGroups != null && RuntimeGroups.Any() && RuntimeJson == null)
            {
                Log.LogError($"{nameof(RuntimeJson)} argument must be specified when {nameof(RuntimeGroups)} is specified.");
                return(false);
            }

            RuntimeGraph runtimeGraph;

            if (!String.IsNullOrEmpty(SourceRuntimeJson))
            {
                if (!File.Exists(SourceRuntimeJson))
                {
                    Log.LogError($"{nameof(SourceRuntimeJson)} did not exist at {SourceRuntimeJson}.");
                    return(false);
                }

                runtimeGraph = JsonRuntimeFormat.ReadRuntimeGraph(SourceRuntimeJson);
            }
            else
            {
                runtimeGraph = new RuntimeGraph();
            }

            foreach (var runtimeGroup in RuntimeGroups.NullAsEmpty().Select(i => new RuntimeGroup(i)))
            {
                runtimeGraph = SafeMerge(runtimeGraph, runtimeGroup);
            }

            ValidateImports(runtimeGraph);

            if (!String.IsNullOrEmpty(RuntimeJson))
            {
                JsonRuntimeFormat.WriteRuntimeGraph(RuntimeJson, runtimeGraph);
            }

            if (!String.IsNullOrEmpty(CompatibilityMap))
            {
                WriteCompatibilityMap(runtimeGraph, CompatibilityMap);
            }

            if (!String.IsNullOrEmpty(RuntimeDirectedGraph))
            {
                WriteRuntimeGraph(runtimeGraph, RuntimeDirectedGraph);
            }

            return(!Log.HasLoggedErrors);
        }
        public static void SaveRuntimeGraph(string filePath, RuntimeGraph runtimeGraph)
        {
            var jsonObjectWriter  = new JsonObjectWriter();
            var runtimeJsonWriter = new RuntimeJsonWriter(jsonObjectWriter);

            JsonRuntimeFormat.WriteRuntimeGraph(runtimeJsonWriter, runtimeGraph);

            using (var file = File.CreateText(filePath))
                using (var jsonWriter = new JsonTextWriter(file))
                {
                    jsonWriter.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii;
                    jsonWriter.Formatting           = Formatting.Indented;
                    jsonObjectWriter.WriteTo(jsonWriter);
                }
        }
        public static List <TfmRidPair> GetAllTfmRidPairs(string supportsFile)
        {
            RuntimeGraph      supportsGraph = JsonRuntimeFormat.ReadRuntimeGraph(supportsFile);
            List <TfmRidPair> tfmRidPairs   = new List <TfmRidPair>();

            foreach (var key in supportsGraph.Supports.Keys)
            {
                CompatibilityProfile compatibilityProfile = null;
                supportsGraph.Supports.TryGetValue(key, out compatibilityProfile);
                foreach (var tfmRidPair in compatibilityProfile.RestoreContexts)
                {
                    tfmRidPairs.Add(new TfmRidPair(tfmRidPair.Framework.GetShortFolderName(), tfmRidPair.RuntimeIdentifier));
                }
            }
            return(tfmRidPairs);
        }
 public TargetFrameworkResolver(string runtimeGraph)
 {
     _conventions         = new ManagedCodeConventions(JsonRuntimeFormat.ReadRuntimeGraph(runtimeGraph));
     _configStringPattern = new PatternSet(
         _conventions.Properties,
         groupPatterns: new PatternDefinition[]
     {
         // In order to use Nuget's asset allocation, the input needs to file paths and should contain a trailing slash.
         new PatternDefinition("{tfm}/"),
         new PatternDefinition("{tfm}-{rid}/")
     },
         pathPatterns: new PatternDefinition[]
     {
         new PatternDefinition("{tfm}/"),
         new PatternDefinition("{tfm}-{rid}/")
     });
 }
Example #19
0
        public static void WriteRuntimeGraph(string filePath, RuntimeGraph runtimeGraph)
        {
            using (var fileStream = new FileStream(filePath, FileMode.Create))
                using (var textWriter = new StreamWriter(fileStream))
                    using (var jsonWriter = new JsonTextWriter(textWriter))
                        using (var writer = new JsonObjectWriter(jsonWriter))
                        {
                            jsonWriter.Formatting = Formatting.Indented;

                            // workaround https://github.com/NuGet/Home/issues/9532
                            writer.WriteObjectStart();

                            JsonRuntimeFormat.WriteRuntimeGraph(writer, runtimeGraph);

                            writer.WriteObjectEnd();
                        }
        }
Example #20
0
        public NuGet.RuntimeModel.RuntimeGraph Collect(IEnumerable <LibraryExport> exports)
        {
            var graph = RuntimeGraph.Empty;

            foreach (var export in exports)
            {
                if (export.Library.Identity.Type == LibraryType.Package)
                {
                    var runtimeJson = ((PackageDescription)export.Library).PackageLibrary.Files.FirstOrDefault(f => f == RuntimeJsonFileName);
                    if (runtimeJson != null)
                    {
                        var runtimeJsonFullName = Path.Combine(export.Library.Path, runtimeJson);
                        graph = RuntimeGraph.Merge(graph, JsonRuntimeFormat.ReadRuntimeGraph(runtimeJsonFullName));
                    }
                }
            }
            return(graph);
        }
Example #21
0
        public static RuntimeGraph Collect(IEnumerable <LibraryDescription> libraries)
        {
            var graph = RuntimeGraph.Empty;

            foreach (var library in libraries)
            {
                if (library.Identity.Type == LibraryType.Package)
                {
                    var runtimeJson = ((PackageDescription)library).PackageLibrary.Files.FirstOrDefault(f => f == RuntimeJsonFileName);
                    if (runtimeJson != null)
                    {
                        var runtimeJsonFullName = Path.Combine(library.Path, runtimeJson);
                        graph = RuntimeGraph.Merge(graph, JsonRuntimeFormat.ReadRuntimeGraph(runtimeJsonFullName));
                    }
                }
            }
            return(graph);
        }
Example #22
0
        internal static void Write(PackageSpec packageSpec, IObjectWriter writer, bool compressed)
        {
            if (packageSpec == null)
            {
                throw new ArgumentNullException(nameof(packageSpec));
            }

            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer));
            }

            SetValue(writer, "title", packageSpec.Title);

#pragma warning disable CS0612 // Type or member is obsolete
            if (!packageSpec.IsDefaultVersion)
            {
                SetValue(writer, "version", packageSpec.Version?.ToFullString());
            }

            SetValue(writer, "description", packageSpec.Description);
            SetArrayValue(writer, "authors", packageSpec.Authors);
            SetValue(writer, "copyright", packageSpec.Copyright);
            SetValue(writer, "language", packageSpec.Language);
            SetArrayValue(writer, "contentFiles", packageSpec.ContentFiles);
            SetDictionaryValue(writer, "packInclude", packageSpec.PackInclude);
            SetPackOptions(writer, packageSpec);
#pragma warning restore CS0612 // Type or member is obsolete
            SetMSBuildMetadata(writer, packageSpec);
#pragma warning disable CS0612 // Type or member is obsolete
            SetDictionaryValues(writer, "scripts", packageSpec.Scripts);
#pragma warning restore CS0612 // Type or member is obsolete


            if (packageSpec.Dependencies.Any())
            {
                SetDependencies(writer, packageSpec.Dependencies);
            }

            SetFrameworks(writer, packageSpec.TargetFrameworks, compressed);

            JsonRuntimeFormat.WriteRuntimeGraph(writer, packageSpec.RuntimeGraph);
        }
        protected override void ExecuteCore()
        {
            RuntimeGraph runtimeGraph = null;

            if (!string.IsNullOrEmpty(RuntimeGraph))
            {
                runtimeGraph = JsonRuntimeFormat.ReadRuntimeGraph(RuntimeGraph);
            }

            Package package = NupkgParser.CreatePackage(PackageTargetPath, runtimeGraph);
            PackageValidationLogger logger = new(Log);

            new CompatibleTfmValidator(NoWarn, null, RunApiCompat, logger).Validate(package);
            new CompatibleFrameworkInPackageValidator(NoWarn, null, logger).Validate(package);
            if (!string.IsNullOrEmpty(BaselinePackageTargetPath))
            {
                Package baselinePackage = NupkgParser.CreatePackage(BaselinePackageTargetPath, runtimeGraph);
                new BaselinePackageValidator(baselinePackage, NoWarn, null, RunApiCompat, logger).Validate(package);
            }
        }
        private static IEnumerable <RuntimeFallbacks> GetRuntimeFallbacks(string[] runtimeGraphFiles, string runtime)
        {
            RuntimeGraph runtimeGraph = RuntimeGraph.Empty;

            foreach (string runtimeGraphFile in runtimeGraphFiles)
            {
                runtimeGraph = RuntimeGraph.Merge(runtimeGraph, JsonRuntimeFormat.ReadRuntimeGraph(runtimeGraphFile));
            }

            foreach (string rid in runtimeGraph.Runtimes.Select(p => p.Key))
            {
                IEnumerable <string> ridFallback = runtimeGraph.ExpandRuntime(rid);

                if (ridFallback.Contains(runtime))
                {
                    // ExpandRuntime return runtime itself as first item so we are skiping it
                    yield return(new RuntimeFallbacks(rid, ridFallback.Skip(1)));
                }
            }
        }
Example #25
0
        /// <summary>
        /// Writes a PackageSpec to an <c>NuGet.Common.IObjectWriter</c> instance.
        /// </summary>
        /// <param name="packageSpec">A <c>PackageSpec</c> instance.</param>
        /// <param name="writer">An <c>NuGet.Common.IObjectWriter</c> instance.</param>
        public static void Write(PackageSpec packageSpec, IObjectWriter writer)
        {
            if (packageSpec == null)
            {
                throw new ArgumentNullException(nameof(packageSpec));
            }

            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer));
            }

            SetValue(writer, "title", packageSpec.Title);

            if (!packageSpec.IsDefaultVersion)
            {
                SetValue(writer, "version", packageSpec.Version?.ToFullString());
            }

            SetValue(writer, "description", packageSpec.Description);
            SetArrayValue(writer, "authors", packageSpec.Authors);
            SetValue(writer, "copyright", packageSpec.Copyright);
            SetValue(writer, "language", packageSpec.Language);
            SetArrayValue(writer, "contentFiles", packageSpec.ContentFiles);
            SetDictionaryValue(writer, "packInclude", packageSpec.PackInclude);
            SetPackOptions(writer, packageSpec);
            SetRestoreSettings(writer, packageSpec);
            SetMSBuildMetadata(writer, packageSpec);
            SetDictionaryValues(writer, "scripts", packageSpec.Scripts);

            if (packageSpec.Dependencies.Any())
            {
                SetDependencies(writer, packageSpec.Dependencies);
            }

            SetFrameworks(writer, packageSpec.TargetFrameworks);

            JsonRuntimeFormat.WriteRuntimeGraph(writer, packageSpec.RuntimeGraph);
        }
Example #26
0
        public NuGet.RuntimeModel.RuntimeGraph Collect(IEnumerable <LibraryExport> exports)
        {
            var graph = RuntimeGraph.Empty;

            foreach (var export in exports)
            {
                if (export.Library.Identity.Type == LibraryType.Package)
                {
                    PackageDescription description = (PackageDescription)export.Library;
                    var runtimeJson = description.PackageLibrary.Files.FirstOrDefault(f => f == RuntimeJsonFileName);
                    if (runtimeJson != null)
                    {
                        // Convert the package-name to lower-case in the path to lookup runtime.json
                        string lowercasedPackageName = description.Identity.Name.ToLower();
                        string pathToPackage         = export.Library.Path.Replace(description.Identity.Name, lowercasedPackageName);

                        var runtimeJsonFullName = Path.Combine(pathToPackage, runtimeJson);
                        graph = RuntimeGraph.Merge(graph, JsonRuntimeFormat.ReadRuntimeGraph(runtimeJsonFullName));
                    }
                }
            }
            return(graph);
        }
Example #27
0
        public void RuntimeGraphRoundTrips()
        {
            string file = $"{nameof(RuntimeGraphRoundTrips)}.json";

            if (File.Exists(file))
            {
                File.Delete(file);
            }

            RuntimeGraph runtimeGraph = new RuntimeGraph(new[] { new RuntimeDescription("RID") });

            // Issue: https://github.com/NuGet/Home/issues/9532
            // When this is fixed, this test should fail. Fix it by deleting the NuGetUtility.WriteRuntimeGraph
            // method and replacing with JsonRuntimeFormat.WriteRuntimeGraph.
            NuGetUtility.WriteRuntimeGraph(file, runtimeGraph);

            File.Exists(file).Should().BeTrue();

            RuntimeGraph readRuntimeGraph = JsonRuntimeFormat.ReadRuntimeGraph(file);

            readRuntimeGraph.Should().NotBeNull();
            readRuntimeGraph.Should().Be(runtimeGraph);
        }
        public RuntimeGraph Collect(LockFile lockFile)
        {
            string userPackageFolder = lockFile.PackageFolders.FirstOrDefault()?.Path;
            var    fallBackFolders   = lockFile.PackageFolders.Skip(1).Select(f => f.Path);
            var    packageResolver   = new FallbackPackagePathResolver(userPackageFolder, fallBackFolders);

            var graph = RuntimeGraph.Empty;

            foreach (var library in lockFile.Libraries)
            {
                if (string.Equals(library.Type, "package", StringComparison.OrdinalIgnoreCase))
                {
                    var runtimeJson = library.Files.FirstOrDefault(f => f == RuntimeJsonFileName);
                    if (runtimeJson != null)
                    {
                        var libraryPath         = packageResolver.GetPackageDirectory(library.Name, library.Version);
                        var runtimeJsonFullName = Path.Combine(libraryPath, runtimeJson);
                        graph = RuntimeGraph.Merge(graph, JsonRuntimeFormat.ReadRuntimeGraph(runtimeJsonFullName));
                    }
                }
            }
            return(graph);
        }
        public static PackageSpec GetPackageSpec(JObject rawPackageSpec, string name, string packageSpecPath, string snapshotValue)
        {
            var packageSpec = new PackageSpec();

            // Parse properties we know about
            var version      = rawPackageSpec["version"];
            var authors      = rawPackageSpec["authors"];
            var contentFiles = rawPackageSpec["contentFiles"];

            packageSpec.Name     = name;
            packageSpec.FilePath = name == null ? null : Path.GetFullPath(packageSpecPath);

            if (version != null)
            {
                try
                {
                    var versionString = version.Value <string>();
                    packageSpec.HasVersionSnapshot = PackageSpecUtility.IsSnapshotVersion(versionString);
                    packageSpec.Version            = PackageSpecUtility.SpecifySnapshot(versionString, snapshotValue);
                }
                catch (Exception ex)
                {
                    var lineInfo = (IJsonLineInfo)version;

                    throw FileFormatException.Create(ex, version, packageSpec.FilePath);
                }
            }

            var packInclude = rawPackageSpec["packInclude"] as JObject;

            if (packInclude != null)
            {
                foreach (var include in packInclude)
                {
                    packageSpec.PackInclude.Add(new KeyValuePair <string, string>(include.Key, include.Value.ToString()));
                }
            }

            packageSpec.Title        = rawPackageSpec.GetValue <string>("title");
            packageSpec.Description  = rawPackageSpec.GetValue <string>("description");
            packageSpec.Authors      = authors == null ? new string[] { } : authors.ValueAsArray <string>();
            packageSpec.ContentFiles = contentFiles == null ? new string[] { } : contentFiles.ValueAsArray <string>();
            packageSpec.Dependencies = new List <LibraryDependency>();
            packageSpec.Copyright    = rawPackageSpec.GetValue <string>("copyright");
            packageSpec.Language     = rawPackageSpec.GetValue <string>("language");


            var buildOptions = rawPackageSpec["buildOptions"] as JObject;

            if (buildOptions != null)
            {
                packageSpec.BuildOptions = new BuildOptions()
                {
                    OutputName = buildOptions.GetValue <string>("outputName")
                };
            }

            var scripts = rawPackageSpec["scripts"] as JObject;

            if (scripts != null)
            {
                foreach (var script in scripts)
                {
                    var value = script.Value;
                    if (value.Type == JTokenType.String)
                    {
                        packageSpec.Scripts[script.Key] = new string[] { value.Value <string>() };
                    }
                    else if (value.Type == JTokenType.Array)
                    {
                        packageSpec.Scripts[script.Key] = script.Value.ValueAsArray <string>();
                    }
                    else
                    {
                        throw FileFormatException.Create(
                                  string.Format("The value of a script in '{0}' can only be a string or an array of strings", PackageSpec.PackageSpecFileName),
                                  value,
                                  packageSpec.FilePath);
                    }
                }
            }

            BuildTargetFrameworks(packageSpec, rawPackageSpec);

            PopulateDependencies(
                packageSpec.FilePath,
                packageSpec.Dependencies,
                rawPackageSpec,
                "dependencies",
                isGacOrFrameworkReference: false);

            packageSpec.PackOptions = GetPackOptions(packageSpec, rawPackageSpec);

            packageSpec.RestoreSettings = GetRestoreSettings(packageSpec, rawPackageSpec);

            packageSpec.RestoreMetadata = GetMSBuildMetadata(packageSpec, rawPackageSpec);

            // Read the runtime graph
            packageSpec.RuntimeGraph = JsonRuntimeFormat.ReadRuntimeGraph(rawPackageSpec);

            // Read the name/path if it exists
            if (packageSpec.Name == null)
            {
                packageSpec.Name = packageSpec.RestoreMetadata?.ProjectName;
            }

            // Use the project.json path if one is set, otherwise use the project path
            if (packageSpec.FilePath == null)
            {
                packageSpec.FilePath = packageSpec.RestoreMetadata?.ProjectJsonPath
                                       ?? packageSpec.RestoreMetadata?.ProjectPath;
            }

            return(packageSpec);
        }
        public override bool Execute()
        {
            if (RuntimeGroups != null && RuntimeGroups.Any() && RuntimeJson == null)
            {
                Log.LogError($"{nameof(RuntimeJson)} argument must be specified when {nameof(RuntimeGroups)} is specified.");
                return(false);
            }

            RuntimeGraph runtimeGraph;

            if (!String.IsNullOrEmpty(SourceRuntimeJson))
            {
                if (!File.Exists(SourceRuntimeJson))
                {
                    Log.LogError($"{nameof(SourceRuntimeJson)} did not exist at {SourceRuntimeJson}.");
                    return(false);
                }

                runtimeGraph = JsonRuntimeFormat.ReadRuntimeGraph(SourceRuntimeJson);
            }
            else
            {
                runtimeGraph = new RuntimeGraph();
            }

            foreach (var runtimeGroup in RuntimeGroups.NullAsEmpty().Select(i => new RuntimeGroup(i)))
            {
                runtimeGraph = SafeMerge(runtimeGraph, runtimeGroup);
            }

            ValidateImports(runtimeGraph);

            if (!String.IsNullOrEmpty(RuntimeJson))
            {
                if (UpdateRuntimeFiles)
                {
                    EnsureWritable(RuntimeJson);
                    JsonRuntimeFormat.WriteRuntimeGraph(RuntimeJson, runtimeGraph);
                }
                else
                {
                    // validate that existing file matches generated file
                    if (!File.Exists(RuntimeJson))
                    {
                        Log.LogError($"{nameof(RuntimeJson)} did not exist at {RuntimeJson} and {nameof(UpdateRuntimeFiles)} was not specified.");
                    }
                    else
                    {
                        var existingRuntimeGraph = JsonRuntimeFormat.ReadRuntimeGraph(RuntimeJson);

                        if (!existingRuntimeGraph.Equals(runtimeGraph))
                        {
                            Log.LogError($"The generated {nameof(RuntimeJson)} differs from {RuntimeJson} and {nameof(UpdateRuntimeFiles)} was not specified.  Please specify {nameof(UpdateRuntimeFiles)}=true to commit the changes.");
                        }
                    }
                }
            }

            if (!String.IsNullOrEmpty(CompatibilityMap))
            {
                var compatibilityMap = GetCompatibilityMap(runtimeGraph);
                if (UpdateRuntimeFiles)
                {
                    EnsureWritable(CompatibilityMap);
                    WriteCompatibilityMap(compatibilityMap, CompatibilityMap);
                }
                else
                {
                    // validate that existing file matches generated file
                    if (!File.Exists(CompatibilityMap))
                    {
                        Log.LogError($"{nameof(CompatibilityMap)} did not exist at {CompatibilityMap} and {nameof(UpdateRuntimeFiles)} was not specified.");
                    }
                    else
                    {
                        var existingCompatibilityMap = ReadCompatibilityMap(CompatibilityMap);

                        if (!CompatibilityMapEquals(existingCompatibilityMap, compatibilityMap))
                        {
                            Log.LogError($"The generated {nameof(CompatibilityMap)} differs from {CompatibilityMap} and {nameof(UpdateRuntimeFiles)} was not specified.  Please specify {nameof(UpdateRuntimeFiles)}=true to commit the changes.");
                        }
                    }
                }
            }

            if (!String.IsNullOrEmpty(RuntimeDirectedGraph))
            {
                WriteRuntimeGraph(runtimeGraph, RuntimeDirectedGraph);
            }

            return(!Log.HasLoggedErrors);
        }