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);
        }
        private static void PopulateDependencies(
            string packageSpecPath,
            IList <LibraryDependency> results,
            JObject settings,
            string propertyName,
            bool isGacOrFrameworkReference)
        {
            var dependencies = settings[propertyName] as JObject;

            if (dependencies != null)
            {
                foreach (var dependency in dependencies)
                {
                    if (string.IsNullOrEmpty(dependency.Key))
                    {
                        throw FileFormatException.Create(
                                  "Unable to resolve dependency ''.",
                                  dependency.Value,
                                  packageSpecPath);
                    }

                    // Support
                    // "dependencies" : {
                    //    "Name" : "1.0"
                    // }

                    var dependencyValue     = dependency.Value;
                    var dependencyTypeValue = LibraryDependencyType.Default;

                    var dependencyIncludeFlagsValue = LibraryIncludeFlags.All;
                    var dependencyExcludeFlagsValue = LibraryIncludeFlags.None;
                    var suppressParentFlagsValue    = LibraryIncludeFlagUtils.DefaultSuppressParent;
                    var noWarn = new List <NuGetLogCode>();

                    // This method handles both the dependencies and framework assembly sections.
                    // Framework references should be limited to references.
                    // Dependencies should allow everything but framework references.
                    var targetFlagsValue = isGacOrFrameworkReference
                                                    ? LibraryDependencyTarget.Reference
                                                    : LibraryDependencyTarget.All & ~LibraryDependencyTarget.Reference;

                    var autoReferenced       = false;
                    var generatePathProperty = false;

                    string dependencyVersionValue = null;
                    var    dependencyVersionToken = dependencyValue;

                    if (dependencyValue.Type == JTokenType.String)
                    {
                        dependencyVersionValue = dependencyValue.Value <string>();
                    }
                    else
                    {
                        if (dependencyValue.Type == JTokenType.Object)
                        {
                            dependencyVersionToken = dependencyValue["version"];
                            if (dependencyVersionToken != null &&
                                dependencyVersionToken.Type == JTokenType.String)
                            {
                                dependencyVersionValue = dependencyVersionToken.Value <string>();
                            }
                        }

                        IEnumerable <string> strings;
                        if (TryGetStringEnumerable(dependencyValue["type"], out strings))
                        {
                            dependencyTypeValue = LibraryDependencyType.Parse(strings);

                            // Types are used at pack time, they should be translated to suppressParent to
                            // provide a matching effect for project to project references.
                            // This should be set before suppressParent is checked.
                            if (!dependencyTypeValue.Contains(LibraryDependencyTypeFlag.BecomesNupkgDependency))
                            {
                                suppressParentFlagsValue = LibraryIncludeFlags.All;
                            }
                            else if (dependencyTypeValue.Contains(LibraryDependencyTypeFlag.SharedFramework))
                            {
                                dependencyIncludeFlagsValue =
                                    LibraryIncludeFlags.Build |
                                    LibraryIncludeFlags.Compile |
                                    LibraryIncludeFlags.Analyzers;
                            }
                        }

                        if (TryGetStringEnumerable(dependencyValue["include"], out strings))
                        {
                            dependencyIncludeFlagsValue = LibraryIncludeFlagUtils.GetFlags(strings);
                        }

                        if (TryGetStringEnumerable(dependencyValue["exclude"], out strings))
                        {
                            dependencyExcludeFlagsValue = LibraryIncludeFlagUtils.GetFlags(strings);
                        }

                        if (TryGetStringEnumerable(dependencyValue["suppressParent"], out strings))
                        {
                            // This overrides any settings that came from the type property.
                            suppressParentFlagsValue = LibraryIncludeFlagUtils.GetFlags(strings);
                        }

                        noWarn = GetNuGetLogCodeEnumerableFromJArray(dependencyValue["noWarn"])
                                 .ToList();

                        var targetToken = dependencyValue["target"];

                        if (targetToken != null)
                        {
                            var targetString = targetToken.Value <string>();

                            targetFlagsValue = LibraryDependencyTargetUtils.Parse(targetString);

                            // Verify that the value specified is package, project, or external project
                            if (!ValidateDependencyTarget(targetFlagsValue))
                            {
                                var message = string.Format(
                                    CultureInfo.CurrentCulture,
                                    Strings.InvalidDependencyTarget,
                                    targetString);

                                throw FileFormatException.Create(message, targetToken, packageSpecPath);
                            }
                        }

                        autoReferenced = GetBoolOrFalse(dependencyValue, "autoReferenced", packageSpecPath);

                        generatePathProperty = GetBoolOrFalse(dependencyValue, "generatePathProperty", packageSpecPath);
                    }

                    VersionRange dependencyVersionRange = null;

                    if (!string.IsNullOrEmpty(dependencyVersionValue))
                    {
                        try
                        {
                            dependencyVersionRange = VersionRange.Parse(dependencyVersionValue);
                        }
                        catch (Exception ex)
                        {
                            throw FileFormatException.Create(
                                      ex,
                                      dependencyVersionToken,
                                      packageSpecPath);
                        }
                    }

                    // Projects and References may have empty version ranges, Packages may not
                    if (dependencyVersionRange == null)
                    {
                        if ((targetFlagsValue & LibraryDependencyTarget.Package) == LibraryDependencyTarget.Package)
                        {
                            throw FileFormatException.Create(
                                      new ArgumentException(Strings.MissingVersionOnDependency),
                                      dependency.Value,
                                      packageSpecPath);
                        }
                        else
                        {
                            // Projects and references with no version property allow all versions
                            dependencyVersionRange = VersionRange.All;
                        }
                    }

                    // the dependency flags are: Include flags - Exclude flags
                    var includeFlags = dependencyIncludeFlagsValue & ~dependencyExcludeFlagsValue;

                    results.Add(new LibraryDependency()
                    {
                        LibraryRange = new LibraryRange()
                        {
                            Name           = dependency.Key,
                            TypeConstraint = targetFlagsValue,
                            VersionRange   = dependencyVersionRange,
                        },
                        Type                 = dependencyTypeValue,
                        IncludeType          = includeFlags,
                        SuppressParent       = suppressParentFlagsValue,
                        AutoReferenced       = autoReferenced,
                        NoWarn               = noWarn.ToList(),
                        GeneratePathProperty = generatePathProperty
                    });
                }
            }
        }
        private static PackOptions GetPackOptions(PackageSpec packageSpec, JObject rawPackageSpec)
        {
            var rawPackOptions = rawPackageSpec.Value <JToken>(PackOptions) as JObject;

            if (rawPackOptions == null)
            {
                packageSpec.Owners = new string[] { };
                packageSpec.Tags   = new string[] { };
                return(new PackOptions
                {
                    PackageType = new PackageType[0]
                });
            }
            var owners = rawPackOptions["owners"];
            var tags   = rawPackOptions["tags"];

            packageSpec.Owners = owners == null?Array.Empty <string>() : owners.ValueAsArray <string>();

            packageSpec.Tags = tags == null?Array.Empty <string>() : tags.ValueAsArray <string>();

            packageSpec.ProjectUrl   = rawPackOptions.GetValue <string>("projectUrl");
            packageSpec.IconUrl      = rawPackOptions.GetValue <string>("iconUrl");
            packageSpec.Summary      = rawPackOptions.GetValue <string>("summary");
            packageSpec.ReleaseNotes = rawPackOptions.GetValue <string>("releaseNotes");
            packageSpec.LicenseUrl   = rawPackOptions.GetValue <string>("licenseUrl");

            packageSpec.RequireLicenseAcceptance = GetBoolOrFalse(rawPackOptions, "requireLicenseAcceptance", packageSpec.FilePath);

            var rawPackageType = rawPackOptions[PackageType];

            if (rawPackageType != null &&
                rawPackageType.Type != JTokenType.String &&
                (rawPackageType.Type != JTokenType.Array || // The array must be all strings.
                 rawPackageType.Type == JTokenType.Array && rawPackageType.Any(t => t.Type != JTokenType.String)) &&
                rawPackageType.Type != JTokenType.Null)
            {
                throw FileFormatException.Create(
                          string.Format(
                              CultureInfo.CurrentCulture,
                              Strings.InvalidPackageType,
                              PackageSpec.PackageSpecFileName),
                          rawPackageType,
                          packageSpec.FilePath);
            }

            IEnumerable <string> packageTypeNames;

            if (!TryGetStringEnumerableFromJArray(rawPackageType, out packageTypeNames))
            {
                packageTypeNames = Enumerable.Empty <string>();
            }

            Dictionary <string, IncludeExcludeFiles> mappings = null;
            IncludeExcludeFiles files = null;
            var rawFiles = rawPackOptions[Files] as JObject;

            if (rawFiles != null)
            {
                files = new IncludeExcludeFiles();
                if (!files.HandleIncludeExcludeFiles(rawFiles))
                {
                    files = null;
                }

                var rawMappings = rawFiles["mappings"] as JObject;

                if (rawMappings != null)
                {
                    mappings = new Dictionary <string, IncludeExcludeFiles>();
                    foreach (var pair in rawMappings)
                    {
                        var key   = pair.Key;
                        var value = pair.Value;
                        if (value.Type == JTokenType.String ||
                            value.Type == JTokenType.Array)
                        {
                            IEnumerable <string> includeFiles;
                            TryGetStringEnumerableFromJArray(value, out includeFiles);
                            var includeExcludeFiles = new IncludeExcludeFiles()
                            {
                                Include = includeFiles?.ToList()
                            };
                            mappings.Add(key, includeExcludeFiles);
                        }
                        else if (value.Type == JTokenType.Object)
                        {
                            var includeExcludeFiles = new IncludeExcludeFiles();
                            if (includeExcludeFiles.HandleIncludeExcludeFiles(value as JObject))
                            {
                                mappings.Add(key, includeExcludeFiles);
                            }
                        }
                    }
                }
            }

            return(new PackOptions
            {
                PackageType = packageTypeNames
                              .Select(name => new PackageType(name, Packaging.Core.PackageType.EmptyVersion))
                              .ToList(),
                IncludeExcludeFiles = files,
                Mappings = mappings
            });
        }
Esempio n. 4
0
        private static void PopulateDownloadDependencies(IList <DownloadDependency> downloadDependencies, JObject properties, string packageSpecPath)
        {
            var splitChars = new[] { ';' };

            var seenIds = new HashSet <string>();

            var downloadDependenciesProperty = properties["downloadDependencies"] as JArray;

            if (downloadDependenciesProperty != null)
            {
                foreach (var dependency in downloadDependenciesProperty.Values <JToken>())
                {
                    if (dependency["name"] == null)
                    {
                        throw FileFormatException.Create(
                                  "Unable to resolve downloadDependency ''.",
                                  dependency,
                                  packageSpecPath);
                    }
                    var name = dependency["name"].Value <string>();
                    if (!seenIds.Add(name))
                    {
                        // package ID already seen, only use first definition.
                        continue;
                    }

                    string versionValue = null;

                    var dependencyVersionToken = dependency["version"];
                    if (dependencyVersionToken != null &&
                        dependencyVersionToken.Type == JTokenType.String)
                    {
                        versionValue = dependencyVersionToken.Value <string>();
                    }

                    VersionRange version = null;

                    if (!string.IsNullOrEmpty(versionValue))
                    {
                        var versions = versionValue.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
                        foreach (var singleVersionValue in versions)
                        {
                            try
                            {
                                version = VersionRange.Parse(singleVersionValue);
                                downloadDependencies.Add(new DownloadDependency(name, version));
                            }
                            catch (Exception ex)
                            {
                                throw FileFormatException.Create(
                                          ex,
                                          dependencyVersionToken,
                                          packageSpecPath);
                            }
                        }
                    }
                    else
                    {
                        throw FileFormatException.Create(
                                  "The version cannot be null or empty",
                                  dependencyVersionToken,
                                  packageSpecPath);
                    }
                }
            }
        }
Esempio n. 5
0
        public static PackageSpec GetPackageSpec(Stream stream, string name, string packageSpecPath)
        {
            // Load the raw JSON into the package spec object
            var reader = new JsonTextReader(new StreamReader(stream));

            JObject rawPackageSpec;

            try
            {
                rawPackageSpec = JObject.Load(reader);
            }
            catch (JsonReaderException ex)
            {
                throw FileFormatException.Create(ex, packageSpecPath);
            }

            var packageSpec = new PackageSpec(rawPackageSpec);

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

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

            if (version == null)
            {
                packageSpec.Version          = new NuGetVersion("1.0.0");
                packageSpec.IsDefaultVersion = true;
            }
            else
            {
                try
                {
                    packageSpec.Version = SpecifySnapshot(version.Value <string>(), snapshotValue: string.Empty);
                }
                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.Owners       = owners == null ? new string[] { } : owners.ValueAsArray <string>();
            packageSpec.ContentFiles = contentFiles == null ? new string[] { } : contentFiles.ValueAsArray <string>();
            packageSpec.Dependencies = new List <LibraryDependency>();
            packageSpec.ProjectUrl   = rawPackageSpec.GetValue <string>("projectUrl");
            packageSpec.IconUrl      = rawPackageSpec.GetValue <string>("iconUrl");
            packageSpec.LicenseUrl   = rawPackageSpec.GetValue <string>("licenseUrl");
            packageSpec.Copyright    = rawPackageSpec.GetValue <string>("copyright");
            packageSpec.Language     = rawPackageSpec.GetValue <string>("language");
            packageSpec.Summary      = rawPackageSpec.GetValue <string>("summary");
            packageSpec.ReleaseNotes = rawPackageSpec.GetValue <string>("releaseNotes");

            var requireLicenseAcceptance = rawPackageSpec["requireLicenseAcceptance"];

            if (requireLicenseAcceptance != null)
            {
                try
                {
                    packageSpec.RequireLicenseAcceptance = rawPackageSpec.GetValue <bool?>("requireLicenseAcceptance") ?? false;
                }
                catch (Exception ex)
                {
                    throw FileFormatException.Create(ex, requireLicenseAcceptance, packageSpecPath);
                }
            }

            packageSpec.Tags = tags == null ? new string[] { } : tags.ValueAsArray <string>();

            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.Tools = ReadTools(packageSpec, rawPackageSpec).ToList();

            packageSpec.PackOptions = GetPackOptions(packageSpec, rawPackageSpec);

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

            return(packageSpec);
        }
Esempio n. 6
0
        private static IEnumerable <ToolDependency> ReadTools(PackageSpec packageSpec, JObject rawPackageSpec)
        {
            var tools = rawPackageSpec["tools"] as JObject;

            if (tools != null)
            {
                foreach (var tool in tools)
                {
                    if (string.IsNullOrEmpty(tool.Key))
                    {
                        throw FileFormatException.Create(
                                  Strings.MissingToolName,
                                  tool.Value,
                                  packageSpec.FilePath);
                    }

                    var    value        = tool.Value;
                    JToken versionToken = null;
                    string versionValue = null;
                    var    imports      = new List <NuGetFramework>();
                    if (value.Type == JTokenType.String)
                    {
                        versionToken = value;
                        versionValue = value.Value <string>();
                    }
                    else
                    {
                        if (value.Type == JTokenType.Object)
                        {
                            versionToken = value["version"];
                            if (versionToken != null && versionToken.Type == JTokenType.String)
                            {
                                versionValue = versionToken.Value <string>();
                            }

                            imports.AddRange(GetImports((JObject)value, packageSpec));
                        }
                    }

                    if (versionValue == null)
                    {
                        throw FileFormatException.Create(
                                  Strings.MissingVersionOnTool,
                                  tool.Value,
                                  packageSpec.FilePath);
                    }

                    VersionRange versionRange;
                    try
                    {
                        versionRange = VersionRange.Parse(versionValue);
                    }
                    catch (Exception ex)
                    {
                        throw FileFormatException.Create(
                                  ex,
                                  versionToken,
                                  packageSpec.FilePath);
                    }

                    yield return(new ToolDependency
                    {
                        LibraryRange = new LibraryRange
                        {
                            Name = tool.Key,
                            TypeConstraint = LibraryDependencyTarget.Package,
                            VersionRange = versionRange
                        },
                        Imports = imports
                    });
                }
            }
        }