Ejemplo n.º 1
0
        private static void AddPackageReferences(PackageSpec spec, IEnumerable <IMSBuildItem> items)
        {
            foreach (var item in GetItemByType(items, "Dependency"))
            {
                var dependency = new LibraryDependency
                {
                    LibraryRange = new LibraryRange(
                        name: item.GetProperty("Id"),
                        versionRange: GetVersionRange(item),
                        typeConstraint: LibraryDependencyTarget.Package),

                    AutoReferenced = IsPropertyTrue(item, "IsImplicitlyDefined"),

                    GeneratePathProperty = IsPropertyTrue(item, "GeneratePathProperty")
                };

                // Add warning suppressions
                foreach (var code in MSBuildStringUtility.GetNuGetLogCodes(item.GetProperty("NoWarn")))
                {
                    dependency.NoWarn.Add(code);
                }

                ApplyIncludeFlags(dependency, item);

                var frameworks = GetFrameworks(item);

                if (frameworks.Count == 0)
                {
                    AddDependencyIfNotExist(spec, dependency);
                }
                else
                {
                    foreach (var framework in frameworks)
                    {
                        AddDependencyIfNotExist(spec, framework, dependency);
                    }
                }
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Convert MSBuild items to a PackageSpec.
        /// </summary>
        public static PackageSpec GetPackageSpec(IEnumerable <IMSBuildItem> items)
        {
            if (items == null)
            {
                throw new ArgumentNullException(nameof(items));
            }

            PackageSpec result = null;

            // There should only be one ProjectSpec per project in the item set,
            // but if multiple do appear take only the first one in an effort
            // to handle this gracefully.
            var specItem = GetItemByType(items, "projectSpec").FirstOrDefault();

            if (specItem != null)
            {
                var typeString  = specItem.GetProperty("ProjectStyle");
                var restoreType = ProjectStyle.Unknown;

                if (!string.IsNullOrEmpty(typeString))
                {
                    Enum.TryParse(typeString, ignoreCase: true, result: out restoreType);
                }

                // Get base spec
                if (restoreType == ProjectStyle.ProjectJson)
                {
                    result = GetProjectJsonSpec(specItem);
                }
                else
                {
                    // Read msbuild data for both non-nuget and .NET Core
                    result = GetBaseSpec(specItem, restoreType);
                }

                // Applies to all types
                result.RestoreMetadata.ProjectStyle      = restoreType;
                result.RestoreMetadata.ProjectPath       = specItem.GetProperty("ProjectPath");
                result.RestoreMetadata.ProjectUniqueName = specItem.GetProperty("ProjectUniqueName");

                if (string.IsNullOrEmpty(result.Name))
                {
                    result.Name = result.RestoreMetadata.ProjectName
                                  ?? result.RestoreMetadata.ProjectUniqueName
                                  ?? Path.GetFileNameWithoutExtension(result.FilePath);
                }

                // Read project references for all
                AddProjectReferences(result, items);

                if (restoreType == ProjectStyle.PackageReference ||
                    restoreType == ProjectStyle.Standalone ||
                    restoreType == ProjectStyle.DotnetCliTool ||
                    restoreType == ProjectStyle.ProjectJson ||
                    restoreType == ProjectStyle.DotnetToolReference)
                {
                    foreach (var source in MSBuildStringUtility.Split(specItem.GetProperty("Sources")))
                    {
                        // Fix slashes incorrectly removed by MSBuild
                        var pkgSource = new PackageSource(FixSourcePath(source));
                        result.RestoreMetadata.Sources.Add(pkgSource);
                    }

                    foreach (var configFilePath in MSBuildStringUtility.Split(specItem.GetProperty("ConfigFilePaths")))
                    {
                        result.RestoreMetadata.ConfigFilePaths.Add(configFilePath);
                    }

                    foreach (var folder in MSBuildStringUtility.Split(specItem.GetProperty("FallbackFolders")))
                    {
                        result.RestoreMetadata.FallbackFolders.Add(folder);
                    }

                    result.RestoreMetadata.PackagesPath = specItem.GetProperty("PackagesPath");

                    result.RestoreMetadata.OutputPath = specItem.GetProperty("OutputPath");
                }

                // Read package references for netcore, tools, and standalone
                if (restoreType == ProjectStyle.PackageReference ||
                    restoreType == ProjectStyle.Standalone ||
                    restoreType == ProjectStyle.DotnetCliTool ||
                    restoreType == ProjectStyle.DotnetToolReference)
                {
                    AddPackageReferences(result, items);
                    AddPackageDownloads(result, items);
                    AddFrameworkReferences(result, items);

                    // Store the original framework strings for msbuild conditionals
                    foreach (var originalFramework in GetFrameworksStrings(specItem))
                    {
                        result.RestoreMetadata.OriginalTargetFrameworks.Add(originalFramework);
                    }
                }

                if (restoreType == ProjectStyle.PackageReference ||
                    restoreType == ProjectStyle.Standalone ||
                    restoreType == ProjectStyle.DotnetToolReference)
                {
                    // Set project version
                    result.Version = GetVersion(specItem);

                    // Add RIDs and Supports
                    result.RuntimeGraph = GetRuntimeGraph(specItem);

                    // Add Target Framework Specific Properties
                    AddTargetFrameworkSpecificProperties(result, items);

                    // Add PackageTargetFallback
                    AddPackageTargetFallbacks(result, items);

                    // Add CrossTargeting flag
                    result.RestoreMetadata.CrossTargeting = IsPropertyTrue(specItem, "CrossTargeting");

                    // Add RestoreLegacyPackagesDirectory flag
                    result.RestoreMetadata.LegacyPackagesDirectory = IsPropertyTrue(
                        specItem,
                        "RestoreLegacyPackagesDirectory");

                    // ValidateRuntimeAssets compat check
                    result.RestoreMetadata.ValidateRuntimeAssets = IsPropertyTrue(specItem, "ValidateRuntimeAssets");

                    // True for .NETCore projects.
                    result.RestoreMetadata.SkipContentFileWrite = IsPropertyTrue(specItem, "SkipContentFileWrite");

                    // Warning properties
                    result.RestoreMetadata.ProjectWideWarningProperties = GetWarningProperties(specItem);

                    // Packages lock file properties
                    result.RestoreMetadata.RestoreLockProperties = GetRestoreLockProperites(specItem);
                }

                if (restoreType == ProjectStyle.PackagesConfig)
                {
                    var pcRestoreMetadata = (PackagesConfigProjectRestoreMetadata)result.RestoreMetadata;
                    // Packages lock file properties
                    pcRestoreMetadata.PackagesConfigPath    = specItem.GetProperty("PackagesConfigPath");
                    pcRestoreMetadata.RestoreLockProperties = GetRestoreLockProperites(specItem);
                }

                if (restoreType == ProjectStyle.ProjectJson)
                {
                    // Check runtime assets by default for project.json
                    result.RestoreMetadata.ValidateRuntimeAssets = true;
                }

                // File assets
                if (restoreType == ProjectStyle.PackageReference ||
                    restoreType == ProjectStyle.ProjectJson ||
                    restoreType == ProjectStyle.Unknown ||
                    restoreType == ProjectStyle.PackagesConfig ||
                    restoreType == ProjectStyle.DotnetToolReference)
                {
                    var projectDir = string.Empty;

                    if (result.RestoreMetadata.ProjectPath != null)
                    {
                        projectDir = Path.GetDirectoryName(result.RestoreMetadata.ProjectPath);
                    }
                }
            }

            return(result);
        }
        /// <summary>
        /// Determine the target framework of an msbuild project.
        /// </summary>
        public static IEnumerable <string> GetProjectFrameworkStrings(
            string projectFilePath,
            string targetFrameworks,
            string targetFramework,
            string targetFrameworkMoniker,
            string targetPlatformIdentifier,
            string targetPlatformVersion,
            string targetPlatformMinVersion,
            bool isXnaWindowsPhoneProject,
            bool isManagementPackProject)
        {
            var frameworks = new SortedSet <string>(StringComparer.OrdinalIgnoreCase);

            // TargetFrameworks property
            frameworks.UnionWith(MSBuildStringUtility.Split(targetFrameworks));

            if (frameworks.Count > 0)
            {
                return(frameworks);
            }

            // TargetFramework property
            var currentFrameworkString = MSBuildStringUtility.TrimAndGetNullForEmpty(targetFramework);

            if (!string.IsNullOrEmpty(currentFrameworkString))
            {
                frameworks.Add(currentFrameworkString);

                return(frameworks);
            }

            // C++ check
            if (projectFilePath?.EndsWith(".vcxproj", StringComparison.OrdinalIgnoreCase) == true)
            {
                // The C++ project does not have a TargetFrameworkMoniker property set.
                // We hard-code the return value to Native.
                frameworks.Add("Native, Version=0.0");

                return(frameworks);
            }

            // The MP project does not have a TargetFrameworkMoniker property set.
            // We hard-code the return value to SCMPInfra.
            if (isManagementPackProject)
            {
                frameworks.Add("SCMPInfra, Version=0.0");

                return(frameworks);
            }

            // UAP/Windows store projects
            var platformIdentifier = MSBuildStringUtility.TrimAndGetNullForEmpty(targetPlatformIdentifier);
            var platformVersion    = MSBuildStringUtility.TrimAndGetNullForEmpty(targetPlatformMinVersion);

            // if targetPlatformMinVersion isn't defined then fallback to targetPlatformVersion
            if (string.IsNullOrEmpty(platformVersion))
            {
                platformVersion = MSBuildStringUtility.TrimAndGetNullForEmpty(targetPlatformVersion);
            }

            // Check for JS project
            if (projectFilePath?.EndsWith(".jsproj", StringComparison.OrdinalIgnoreCase) == true)
            {
                // JavaScript apps do not have a TargetFrameworkMoniker property set.
                // We read the TargetPlatformIdentifier and targetPlatformMinVersion instead
                // use the default values for JS if they were not given
                if (string.IsNullOrEmpty(platformVersion))
                {
                    platformVersion = "0.0";
                }

                if (string.IsNullOrEmpty(platformIdentifier))
                {
                    platformIdentifier = FrameworkConstants.FrameworkIdentifiers.Windows;
                }

                frameworks.Add($"{platformIdentifier}, Version={platformVersion}");

                return(frameworks);
            }

            if (!string.IsNullOrEmpty(platformVersion) &&
                StringComparer.OrdinalIgnoreCase.Equals(platformIdentifier, "UAP"))
            {
                // Use the platform id and versions, this is done for UAP projects
                frameworks.Add($"{platformIdentifier}, Version={platformVersion}");

                return(frameworks);
            }

            // TargetFrameworkMoniker
            currentFrameworkString = MSBuildStringUtility.TrimAndGetNullForEmpty(targetFrameworkMoniker);

            if (!string.IsNullOrEmpty(currentFrameworkString))
            {
                // XNA project lies about its true identity, reporting itself as a normal .NET 4.0 project.
                // We detect it and changes its target framework to Silverlight4-WindowsPhone71
                if (isXnaWindowsPhoneProject &&
                    ".NETFramework,Version=v4.0".Equals(currentFrameworkString, StringComparison.OrdinalIgnoreCase))
                {
                    currentFrameworkString = "Silverlight,Version=v4.0,Profile=WindowsPhone71";
                }

                frameworks.Add(currentFrameworkString);

                return(frameworks);
            }

            // Default to unsupported it no framework can be found.
            if (frameworks.Count < 1)
            {
                frameworks.Add(NuGetFramework.UnsupportedFramework.ToString());
            }

            return(frameworks);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Convert MSBuild items to a PackageSpec.
        /// </summary>
        public static PackageSpec GetPackageSpec(IEnumerable <IMSBuildItem> items)
        {
            if (items == null)
            {
                throw new ArgumentNullException(nameof(items));
            }

            PackageSpec result = null;

            // There should only be one ProjectSpec per project in the item set,
            // but if multiple do appear take only the first one in an effort
            // to handle this gracefully.
            var specItem = GetItemByType(items, "projectSpec").FirstOrDefault();

            if (specItem != null)
            {
                ProjectStyle restoreType   = GetProjectStyle(specItem);
                bool         isCpvmEnabled = IsCentralVersionsManagementEnabled(specItem, restoreType);

                // Get base spec
                if (restoreType == ProjectStyle.ProjectJson)
                {
                    result = GetProjectJsonSpec(specItem);
                }
                else
                {
                    // Read msbuild data for PR and related projects
                    result = GetBaseSpec(specItem, restoreType, items);
                }

                // Applies to all types
                result.RestoreMetadata.ProjectStyle      = restoreType;
                result.RestoreMetadata.ProjectPath       = specItem.GetProperty("ProjectPath");
                result.RestoreMetadata.ProjectUniqueName = specItem.GetProperty("ProjectUniqueName");

                if (string.IsNullOrEmpty(result.Name))
                {
                    result.Name = result.RestoreMetadata.ProjectName
                                  ?? result.RestoreMetadata.ProjectUniqueName
                                  ?? Path.GetFileNameWithoutExtension(result.FilePath);
                }

                // Read project references for all
                AddProjectReferences(result, items);

                if (restoreType == ProjectStyle.PackageReference ||
                    restoreType == ProjectStyle.Standalone ||
                    restoreType == ProjectStyle.DotnetCliTool ||
                    restoreType == ProjectStyle.ProjectJson ||
                    restoreType == ProjectStyle.DotnetToolReference ||
                    restoreType == ProjectStyle.PackagesConfig)
                {
                    foreach (var source in MSBuildStringUtility.Split(specItem.GetProperty("Sources")))
                    {
                        // Fix slashes incorrectly removed by MSBuild
                        var pkgSource = new PackageSource(FixSourcePath(source));
                        result.RestoreMetadata.Sources.Add(pkgSource);
                    }

                    foreach (var configFilePath in MSBuildStringUtility.Split(specItem.GetProperty("ConfigFilePaths")))
                    {
                        result.RestoreMetadata.ConfigFilePaths.Add(configFilePath);
                    }

                    foreach (var folder in MSBuildStringUtility.Split(specItem.GetProperty("FallbackFolders")))
                    {
                        result.RestoreMetadata.FallbackFolders.Add(folder);
                    }

                    result.RestoreMetadata.PackagesPath = specItem.GetProperty("PackagesPath");
                    result.RestoreMetadata.OutputPath   = specItem.GetProperty("OutputPath");
                }

                // Read package references for netcore, tools, and standalone
                if (restoreType == ProjectStyle.PackageReference ||
                    restoreType == ProjectStyle.Standalone ||
                    restoreType == ProjectStyle.DotnetCliTool ||
                    restoreType == ProjectStyle.DotnetToolReference)
                {
                    AddPackageReferences(result, items, isCpvmEnabled);
                    AddPackageDownloads(result, items);
                    AddFrameworkReferences(result, items);

                    // Store the original framework strings for msbuild conditionals
                    result.TargetFrameworks.ForEach(tfi =>
                                                    result.RestoreMetadata.OriginalTargetFrameworks.Add(
                                                        !string.IsNullOrEmpty(tfi.TargetAlias) ?
                                                        tfi.TargetAlias :
                                                        tfi.FrameworkName.GetShortFolderName()));
                }

                if (restoreType == ProjectStyle.PackageReference ||
                    restoreType == ProjectStyle.Standalone ||
                    restoreType == ProjectStyle.DotnetToolReference)
                {
                    // Set project version
                    result.Version = GetVersion(specItem);

                    // Add RIDs and Supports
                    result.RuntimeGraph = GetRuntimeGraph(specItem);

                    // Add CrossTargeting flag
                    result.RestoreMetadata.CrossTargeting = IsPropertyTrue(specItem, "CrossTargeting");

                    // Add RestoreLegacyPackagesDirectory flag
                    result.RestoreMetadata.LegacyPackagesDirectory = IsPropertyTrue(
                        specItem,
                        "RestoreLegacyPackagesDirectory");

                    // ValidateRuntimeAssets compat check
                    result.RestoreMetadata.ValidateRuntimeAssets = IsPropertyTrue(specItem, "ValidateRuntimeAssets");

                    // True for .NETCore projects.
                    result.RestoreMetadata.SkipContentFileWrite = IsPropertyTrue(specItem, "SkipContentFileWrite");

                    // Warning properties
                    result.RestoreMetadata.ProjectWideWarningProperties = GetWarningProperties(specItem);

                    // Packages lock file properties
                    result.RestoreMetadata.RestoreLockProperties = GetRestoreLockProperites(specItem);
                }

                if (restoreType == ProjectStyle.PackagesConfig)
                {
                    var pcRestoreMetadata = (PackagesConfigProjectRestoreMetadata)result.RestoreMetadata;
                    // Packages lock file properties
                    pcRestoreMetadata.PackagesConfigPath = specItem.GetProperty("PackagesConfigPath");
                    pcRestoreMetadata.RepositoryPath     = specItem.GetProperty("RepositoryPath");
                    var solutionDir = specItem.GetProperty("SolutionDir");
                    if (string.IsNullOrEmpty(pcRestoreMetadata.RepositoryPath) && !string.IsNullOrEmpty(solutionDir) && solutionDir != "*Undefined*")
                    {
                        pcRestoreMetadata.RepositoryPath = Path.Combine(
                            solutionDir,
                            "packages"
                            );
                    }
                    pcRestoreMetadata.RestoreLockProperties = GetRestoreLockProperites(specItem);
                }

                if (restoreType == ProjectStyle.ProjectJson)
                {
                    // Check runtime assets by default for project.json
                    result.RestoreMetadata.ValidateRuntimeAssets = true;
                }

                result.RestoreMetadata.CentralPackageVersionsEnabled = isCpvmEnabled;
            }

            return(result);
        }
        internal static NuGetFramework GetProjectFramework(
            string projectFilePath,
            string targetFrameworkMoniker,
            string targetPlatformMoniker,
            string targetPlatformIdentifier,
            string targetPlatformVersion,
            string targetPlatformMinVersion,
            bool isXnaWindowsPhoneProject,
            bool isManagementPackProject)
        {
            // C++ check
            if (projectFilePath?.EndsWith(".vcxproj", StringComparison.OrdinalIgnoreCase) == true)
            {
                // The C++ project does not have a TargetFrameworkMoniker property set.
                // We hard-code the return value to Native.
                return(NuGetFramework.Parse("Native, Version=0.0"));
            }

            // The MP project does not have a TargetFrameworkMoniker property set.
            // We hard-code the return value to SCMPInfra.
            if (isManagementPackProject)
            {
                return(NuGetFramework.Parse("SCMPInfra, Version=0.0"));
            }

            // UAP/Windows store projects
            var platformMoniker           = MSBuildStringUtility.TrimAndGetNullForEmpty(targetPlatformMoniker);
            var platformMonikerIdentifier = GetParts(platformMoniker).FirstOrDefault();

            var platformIdentifier = MSBuildStringUtility.TrimAndGetNullForEmpty(targetPlatformIdentifier);
            var platformMinVersion = MSBuildStringUtility.TrimAndGetNullForEmpty(targetPlatformMinVersion);
            var platformVersion    = MSBuildStringUtility.TrimAndGetNullForEmpty(targetPlatformVersion);

            var effectivePlatformVersion    = platformMinVersion ?? platformVersion;
            var effectivePlatformIdentifier = platformMonikerIdentifier ?? platformIdentifier;

            // Check for JS project
            if (projectFilePath?.EndsWith(".jsproj", StringComparison.OrdinalIgnoreCase) == true)
            {
                // JavaScript apps do not have a TargetFrameworkMoniker property set.
                // We read the TargetPlatformIdentifier and targetPlatformMinVersion instead
                // use the default values for JS if they were not given

                // Prefer moniker over individual properties
                if (!string.IsNullOrEmpty(platformMoniker))
                {
                    return(GetFrameworkFromMoniker(platformMonikerIdentifier, platformMoniker, platformMinVersion));
                }

                if (string.IsNullOrEmpty(effectivePlatformVersion))
                {
                    effectivePlatformVersion = "0.0";
                }

                if (string.IsNullOrEmpty(effectivePlatformIdentifier))
                {
                    effectivePlatformIdentifier = FrameworkConstants.FrameworkIdentifiers.Windows;
                }

                return(NuGetFramework.Parse($"{effectivePlatformIdentifier}, Version={effectivePlatformVersion}"));
            }

            if (StringComparer.OrdinalIgnoreCase.Equals(effectivePlatformIdentifier, "UAP"))
            {
                // Use the platform id and versions, this is done for UAP projects
                // Prefer moniker over individual properties
                if (!string.IsNullOrEmpty(platformMoniker))
                {
                    return(GetFrameworkFromMoniker(effectivePlatformIdentifier, platformMoniker, platformMinVersion));
                }
                if (!string.IsNullOrEmpty(effectivePlatformVersion))
                {
                    return(NuGetFramework.Parse($"{effectivePlatformIdentifier}, Version={effectivePlatformVersion}"));
                }
            }

            // TargetFrameworkMoniker
            var currentFrameworkString = MSBuildStringUtility.TrimAndGetNullForEmpty(targetFrameworkMoniker);

            if (!string.IsNullOrEmpty(currentFrameworkString))
            {
                // XNA project lies about its true identity, reporting itself as a normal .NET 4.0 project.
                // We detect it and changes its target framework to Silverlight4-WindowsPhone71
                if (isXnaWindowsPhoneProject &&
                    ".NETFramework,Version=v4.0".Equals(currentFrameworkString, StringComparison.OrdinalIgnoreCase))
                {
                    currentFrameworkString = "Silverlight,Version=v4.0,Profile=WindowsPhone71";
                    return(NuGetFramework.Parse(currentFrameworkString));
                }
                NuGetFramework framework = NuGetFramework.ParseComponents(currentFrameworkString, platformMoniker);

                return(framework);
            }

            // Default to unsupported it no framework was found.
            return(NuGetFramework.UnsupportedFramework);
        }