static HashSet <string> GetFrameworksStrings(ProjectItem item)
        {
            var frameworks = new HashSet <string> (StringComparer.OrdinalIgnoreCase);

            string frameworksString = item.Metadata.GetValue("TargetFrameworks");

            if (!string.IsNullOrEmpty(frameworksString))
            {
                frameworks.UnionWith(MSBuildStringUtility.Split(frameworksString));
            }

            return(frameworks);
        }
        static LibraryIncludeFlags GetIncludeFlags(string value, LibraryIncludeFlags defaultValue)
        {
            var parts = MSBuildStringUtility.Split(value);

            if (parts.Length > 0)
            {
                return(LibraryIncludeFlagUtils.GetFlags(parts));
            }
            else
            {
                return(defaultValue);
            }
        }
        static void AddSources(List <PackageSource> sources, IDotNetProject project, string propertyName)
        {
            string sourcesProperty = project.EvaluatedProperties.GetValue(propertyName);

            if (string.IsNullOrEmpty(sourcesProperty))
            {
                return;
            }

            var additionalPackageSources = MSBuildStringUtility.Split(sourcesProperty)
                                           .Select(source => CreatePackageSource(project.BaseDirectory, source));

            sources.AddRange(additionalPackageSources);
        }
        static void AddFolders(List <string> folders, IDotNetProject project, string propertyName)
        {
            string foldersProperty = project.EvaluatedProperties.GetValue(propertyName);

            if (string.IsNullOrEmpty(foldersProperty))
            {
                return;
            }

            var normalizedFolders = MSBuildStringUtility.Split(foldersProperty)
                                    .Select(folder => NormalizeFolder(project.BaseDirectory, folder));

            folders.AddRange(normalizedFolders);
        }
        /// <summary>
        /// Helper method to join across multiple values of a commandline option.
        /// E.g. -
        /// Input - { "net45; netcoreapp1.1", "netstandard1.6; net46", "net451"}
        /// Output - [ "net45", "netcoreapp1.1", "netstandard1.6", "net46", "net451" ]
        /// </summary>
        /// <param name="inputs">List of values.</param>
        /// <returns>A string array of values joined from across multiple input values.</returns>
        public static string[] SplitAndJoinAcrossMultipleValues(IList <string> inputs)
        {
            var result = new List <string>();

            if (inputs?.Count > 0)
            {
                foreach (var input in inputs)
                {
                    result.AddRange(MSBuildStringUtility.Split(input));
                }
            }

            return(result.ToArray());
        }
Esempio n. 6
0
        static RuntimeGraph GetRuntimeGraph(IDotNetProject project)
        {
            var runtimes = MSBuildStringUtility.Split(project.EvaluatedProperties.GetValue("RuntimeIdentifiers"))
                           .Distinct(StringComparer.Ordinal)
                           .Select(rid => new RuntimeDescription(rid))
                           .ToList();

            var supports = MSBuildStringUtility.Split(project.EvaluatedProperties.GetValue("RuntimeSupports"))
                           .Distinct(StringComparer.Ordinal)
                           .Select(s => new CompatibilityProfile(s))
                           .ToList();

            return(new RuntimeGraph(runtimes, supports));
        }
        internal static TargetFrameworkInformation ToTargetFrameworkInformation(
            IVsTargetFrameworkInfo targetFrameworkInfo)
        {
            var tfi = new TargetFrameworkInformation
            {
                FrameworkName = NuGetFramework.Parse(targetFrameworkInfo.TargetFrameworkMoniker)
            };

            var ptf = MSBuildStringUtility.Split(GetPropertyValueOrNull(targetFrameworkInfo.Properties, ProjectBuildProperties.PackageTargetFallback))
                      .Select(NuGetFramework.Parse)
                      .ToList();

            var atf = MSBuildStringUtility.Split(GetPropertyValueOrNull(targetFrameworkInfo.Properties, ProjectBuildProperties.AssetTargetFallback))
                      .Select(NuGetFramework.Parse)
                      .ToList();

            // Update TFI with fallback properties
            AssetTargetFallbackUtility.ApplyFramework(tfi, ptf, atf);

            if (targetFrameworkInfo.PackageReferences != null)
            {
                tfi.Dependencies.AddRange(
                    targetFrameworkInfo.PackageReferences
                    .Cast <IVsReferenceItem>()
                    .Select(ToPackageLibraryDependency));
            }

            if (targetFrameworkInfo is IVsTargetFrameworkInfo2 targetFrameworkInfo2)
            {
                if (targetFrameworkInfo2.PackageDownloads != null)
                {
                    tfi.DownloadDependencies.AddRange(
                        targetFrameworkInfo2.PackageDownloads
                        .Cast <IVsReferenceItem>()
                        .Select(ToPackageDownloadDependency));
                }

                if (targetFrameworkInfo2.FrameworkReferences != null)
                {
                    tfi.FrameworkReferences.AddRange(
                        targetFrameworkInfo2.FrameworkReferences
                        .Cast <IVsReferenceItem>()
                        .Select(e => e.Name));
                }
            }

            return(tfi);
        }
Esempio n. 8
0
        public async Task <string[]> GetProjectTypeGuidsAsync()
        {
            var typeGuid = Project.GetProjectTypeGuids();

            var projectTypeGuids = await BuildProperties.GetPropertyValueAsync(ProjectBuildProperties.ProjectTypeGuids);

            if (!string.IsNullOrEmpty(projectTypeGuids))
            {
                return(MSBuildStringUtility.Split(projectTypeGuids));
            }
            else if (!string.IsNullOrEmpty(typeGuid))
            {
                return(MSBuildStringUtility.Split(typeGuid));
            }

            return(Array.Empty <string>());
        }
Esempio n. 9
0
        private static IEnumerable <string> GetProjectFrameworks(Project project)
        {
            var frameworks = project
                             .AllEvaluatedProperties
                             .Where(p => p.Name.Equals(FRAMEWORK_TAG, StringComparison.OrdinalIgnoreCase))
                             .Select(p => p.EvaluatedValue);

            if (!frameworks.Any())
            {
                var frameworksString = project
                                       .AllEvaluatedProperties
                                       .Where(p => p.Name.Equals(FRAMEWORKS_TAG, StringComparison.OrdinalIgnoreCase))
                                       .Select(p => p.EvaluatedValue)
                                       .FirstOrDefault();
                frameworks = MSBuildStringUtility.Split(frameworksString);
            }
            return(frameworks);
        }
        /// <summary>
        /// Gets the framework references per target framework for the specified project.
        /// </summary>
        /// <param name="project">The <see cref="ProjectInstance" /> to get framework references for.</param>
        /// <returns>A <see cref="List{FrameworkDependency}" /> containing the framework references for the specified project.</returns>
        internal static List <FrameworkDependency> GetFrameworkReferences(IMSBuildProject project)
        {
            // Get the unique FrameworkReference items, ignoring duplicates
            var frameworkReferenceItems = project.GetItems("FrameworkReference").Distinct(ProjectItemInstanceEvaluatedIncludeComparer.Instance).ToList();

            // For best performance, its better to create a list with the exact number of items needed rather than using a LINQ statement or AddRange.  This is because if the list
            // is not allocated with enough items, the list has to be grown which can slow things down
            var frameworkDependencies = new List <FrameworkDependency>(frameworkReferenceItems.Count);

            foreach (var frameworkReferenceItem in frameworkReferenceItems)
            {
                var privateAssets = MSBuildStringUtility.Split(frameworkReferenceItem.GetProperty("PrivateAssets"));

                frameworkDependencies.Add(new FrameworkDependency(frameworkReferenceItem.Identity, FrameworkDependencyFlagsUtils.GetFlags(privateAssets)));
            }

            return(frameworkDependencies);
        }
Esempio n. 11
0
        static IEnumerable <string> GetOriginalTargetFrameworks(IDotNetProject project)
        {
            var properties = project.EvaluatedProperties;

            if (properties != null)
            {
                string targetFramework = properties.GetValue("TargetFramework");
                if (targetFramework != null)
                {
                    return(new [] { targetFramework });
                }

                string targetFrameworks = properties.GetValue("TargetFrameworks");
                return(MSBuildStringUtility.Split(targetFrameworks));
            }

            return(new string[0]);
        }
Esempio n. 12
0
        public static SimpleTestProjectContext CreateProject(string projectName,
                                                             SimpleTestPathContext pathContext,
                                                             string projectFrameworks)
        {
            var settings = Settings.LoadDefaultSettings(Path.GetDirectoryName(pathContext.NuGetConfig), Path.GetFileName(pathContext.NuGetConfig), null);
            var project  = SimpleTestProjectContext.CreateNETCoreWithSDK(
                projectName: projectName,
                solutionRoot: pathContext.SolutionRoot,
                frameworks: MSBuildStringUtility.Split(projectFrameworks));

            project.FallbackFolders      = (IList <string>)SettingsUtility.GetFallbackPackageFolders(settings);
            project.GlobalPackagesFolder = SettingsUtility.GetGlobalPackagesFolder(settings);
            var packageSourceProvider = new PackageSourceProvider(settings);

            project.Sources = packageSourceProvider.LoadPackageSources();

            project.Save();
            return(project);
        }
Esempio n. 13
0
        /// <summary>
        /// Adds a dependency to the current package.
        /// </summary>
        /// <param name="id">The identifier of the dependency.</param>
        /// <param name="version">The <see cref="VersionRange" /> of the dependency.</param>
        /// <param name="targetFramework">The <see cref="NuGetFramework" /> for the dependency.</param>
        /// <param name="include">An optional <see cref="LibraryIncludeFlags" /> representing the assets to include for the dependency.</param>
        /// <param name="exclude">An optional <see cref="LibraryIncludeFlags" /> representing the assets to exclude from the dependency.</param>
        /// <returns>The current <see cref="PackageRepository" />.</returns>
        public PackageRepository Dependency(string id, VersionRange version, NuGetFramework targetFramework, LibraryIncludeFlags?include = null, LibraryIncludeFlags?exclude = null)
        {
            _packageManifest.Metadata.DependencyGroups = _packageManifest.Metadata.DependencyGroups.Concat(new List <PackageDependencyGroup>
            {
                new PackageDependencyGroup(
                    targetFramework ?? NuGetFramework.AnyFramework,
                    new List <PackageDependency>
                {
                    new PackageDependency(
                        id,
                        version,
                        include == null ? null : MSBuildStringUtility.Split(include.ToString(), ','),
                        exclude == null ? null : MSBuildStringUtility.Split(exclude.ToString(), ',')),
                }),
            });

            _packageManifest.Save();

            return(this);
        }
        private IList <string> GetFallbackFolders(ISettings settings, bool shouldThrow = true)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var fallbackFolders = MSBuildStringUtility.Split(_vsProjectAdapter.RestoreFallbackFolders).AsEnumerable();

            if (ShouldReadFromSettings(fallbackFolders))
            {
                fallbackFolders = SettingsUtility.GetFallbackPackageFolders(settings);
            }
            else
            {
                fallbackFolders = VSRestoreSettingsUtilities.HandleClear(fallbackFolders);
            }

            // Add additional fallback folders
            fallbackFolders = fallbackFolders.Concat(MSBuildStringUtility.Split(_vsProjectAdapter.RestoreAdditionalProjectFallbackFolders));

            return(fallbackFolders.Select(e => UriUtility.GetAbsolutePathFromFile(_projectFullPath, e)).ToList());
        }
        private IList <PackageSource> GetSources(ISettings settings, bool shouldThrow = true)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var sources = MSBuildStringUtility.Split(_vsProjectAdapter.RestoreSources).AsEnumerable();

            if (ShouldReadFromSettings(sources))
            {
                sources = SettingsUtility.GetEnabledSources(settings).Select(e => e.Source);
            }
            else
            {
                sources = VSRestoreSettingsUtilities.HandleClear(sources);
            }

            // Add additional sources
            sources = sources.Concat(MSBuildStringUtility.Split(_vsProjectAdapter.RestoreAdditionalProjectSources));

            return(sources.Select(e => new PackageSource(UriUtility.GetAbsolutePathFromFile(_projectFullPath, e))).ToList());
        }
Esempio n. 16
0
        public async Task VSSolutionRestoreService_VSRestoreSettingsUtilities_Integration(string restoreSources, string restoreAdditionalProjectSources, string expectedRestoreSources, string restoreFallbackFolders, string restoreAdditionalFallbackFolders, string expectedFallbackFolders)
        {
            var cps = NewCpsProject(@"{ }");
            var pri = cps.Builder
                      .WithTool("Foo.Test", "2.0.0")
                      .WithTargetFrameworkInfo(
                new VsTargetFrameworkInfo(
                    "netcoreapp2.0",
                    Enumerable.Empty <IVsReferenceItem>(),
                    Enumerable.Empty <IVsReferenceItem>(),
                    new[] { new VsProjectProperty("RestoreSources", restoreSources),
                            new VsProjectProperty("RestoreFallbackFolders", restoreFallbackFolders),
                            new VsProjectProperty("RestoreAdditionalProjectSources", restoreAdditionalProjectSources),
                            new VsProjectProperty("RestoreAdditionalProjectFallbackFolders", restoreAdditionalFallbackFolders) }))
                      .Build();
            var projectFullPath = cps.ProjectFullPath;

            // Act
            var actualRestoreSpec = await CaptureNominateResultAsync(projectFullPath, pri);

            // Assert
            SpecValidationUtility.ValidateDependencySpec(actualRestoreSpec);

            var actualProjectSpec = actualRestoreSpec.GetProjectSpec(projectFullPath);

            Assert.NotNull(actualProjectSpec);

            var specSources = VSRestoreSettingsUtilities.GetSources(NullSettings.Instance, actualProjectSpec).Select(e => e.Source);

            var expectedSources = MSBuildStringUtility.Split(expectedRestoreSources);

            Assert.True(Enumerable.SequenceEqual(expectedSources.OrderBy(t => t), specSources.OrderBy(t => t)));

            var specFallback = VSRestoreSettingsUtilities.GetFallbackFolders(NullSettings.Instance, actualProjectSpec);

            var expectedFallback = MSBuildStringUtility.Split(expectedFallbackFolders);

            Assert.True(
                Enumerable.SequenceEqual(expectedFallback.OrderBy(t => t), specFallback.OrderBy(t => t)),
                "expected: " + string.Join(",", expectedFallback.ToArray()) + "\nactual: " + string.Join(",", specFallback.ToArray()));
        }
Esempio n. 17
0
        public static SimpleTestPackageContext CreatePackage(string packageId       = "packageX",
                                                             string packageVersion  = "1.0.0",
                                                             string frameworkString = null)
        {
            var package = new SimpleTestPackageContext()
            {
                Id      = packageId,
                Version = packageVersion
            };
            var frameworks = MSBuildStringUtility.Split(frameworkString);

            // Make the package Compatible with specific frameworks
            frameworks?
            .ToList()
            .ForEach(f => package.AddFile($"lib/{f}/a.dll"));

            // To ensure that the nuspec does not have System.Runtime.dll
            package.Nuspec = GetNetCoreNuspec(packageId, packageVersion);

            return(package);
        }
Esempio n. 18
0
        public static PackageReferenceArgs GetPackageReferenceArgs(string packageId, string packageVersion, SimpleTestProjectContext project,
                                                                   string frameworks = "", string packageDirectory = "", string sources = "", bool noRestore = false, bool noVersion = false)
        {
            var logger            = new TestCommandOutputLogger();
            var packageDependency = new PackageDependency(packageId, VersionRange.Parse(packageVersion));
            var dgFilePath        = string.Empty;

            if (!noRestore)
            {
                dgFilePath = CreateDGFileForProject(project);
            }
            return(new PackageReferenceArgs(project.ProjectPath, packageDependency, logger)
            {
                Frameworks = MSBuildStringUtility.Split(frameworks),
                Sources = MSBuildStringUtility.Split(sources),
                PackageDirectory = packageDirectory,
                NoRestore = noRestore,
                NoVersion = noVersion,
                DgFilePath = dgFilePath
            });
        }
        /// <summary>
        /// Gets the package downloads for the specified project.
        /// </summary>
        /// <param name="project">The <see cref="ProjectInstance" /> to get package downloads for.</param>
        /// <returns>An <see cref="IEnumerable{DownloadDependency}" /> containing the package downloads for the specified project.</returns>
        internal static IEnumerable <DownloadDependency> GetPackageDownloads(IMSBuildProject project)
        {
            // Get the distinct PackageDownload items, ignoring duplicates
            foreach (var projectItemInstance in project.GetItems("PackageDownload").Distinct(ProjectItemInstanceEvaluatedIncludeComparer.Instance))
            {
                string id = projectItemInstance.Identity;

                // PackageDownload items can contain multiple versions
                foreach (var version in MSBuildStringUtility.Split(projectItemInstance.GetProperty("Version")))
                {
                    // Validate the version range
                    VersionRange versionRange = !string.IsNullOrWhiteSpace(version) ? VersionRange.Parse(version) : VersionRange.All;

                    if (!(versionRange.HasLowerAndUpperBounds && versionRange.MinVersion.Equals(versionRange.MaxVersion)))
                    {
                        throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.Error_PackageDownload_OnlyExactVersionsAreAllowed, versionRange.OriginalString));
                    }

                    yield return(new DownloadDependency(id, versionRange));
                }
            }
        }
Esempio n. 20
0
        public static SimpleTestProjectContext CreateProject(string projectName,
                                                             SimpleTestPathContext pathContext,
                                                             SimpleTestPackageContext package,
                                                             string projectFrameworks,
                                                             string packageFramework = null)
        {
            var project = SimpleTestProjectContext.CreateNETCoreWithSDK(
                projectName: projectName,
                solutionRoot: pathContext.SolutionRoot,
                frameworks: MSBuildStringUtility.Split(projectFrameworks));

            if (packageFramework == null)
            {
                project.AddPackageToAllFrameworks(package);
            }
            else
            {
                project.AddPackageToFramework(packageFramework, package);
            }
            project.Save();
            return(project);
        }
Esempio n. 21
0
        static IEnumerable <string> GetOriginalTargetFrameworks(IDotNetProject project)
        {
            var properties = project.EvaluatedProperties;

            if (properties != null)
            {
                string targetFramework = properties.GetValue("TargetFramework");
                if (targetFramework != null)
                {
                    return(new [] { targetFramework });
                }

                string targetFrameworks = properties.GetValue("TargetFrameworks");
                if (targetFrameworks != null)
                {
                    return(MSBuildStringUtility.Split(targetFrameworks));
                }
            }

            var framework = NuGetFramework.Parse(project.TargetFrameworkMoniker.ToString());

            return(new [] { framework.GetShortFolderName() });
        }
Esempio n. 22
0
        private ITaskItem AssignPropertiesForSingleReference(ITaskItem project, NuGetFramework currentProjectTargetFramework)
        {
            var itemWithProperties = new TaskItem(project);
            var targetFrameworks   = project.GetMetadata("TargetFrameworks");

            if (string.IsNullOrEmpty(targetFrameworks))
            {
                // No target frameworks set, nothing to do.
                return(itemWithProperties);
            }

            var possibleTargetFrameworks = MSBuildStringUtility.Split(targetFrameworks);
            var nearestNuGetFramework    = NuGetFrameworkUtility.GetNearest(possibleTargetFrameworks, currentProjectTargetFramework, NuGetFramework.Parse);

            itemWithProperties.SetMetadata("NearestTargetFramework", nearestNuGetFramework ?? FrameworkConstants.SpecialIdentifiers.Unsupported);

            if (nearestNuGetFramework == null)
            {
                Log.LogError(string.Format(Strings.NoCompatibleTargetFramework, project.ItemSpec, CurrentProjectTargetFramework, targetFrameworks));
            }

            return(itemWithProperties);
        }
Esempio n. 23
0
        public async Task NominateProjectAsync_RestoreSettingsClear(string restorePackagesPath, string restoreSources, string fallbackFolders)
        {
            var cps             = NewCpsProject("{ }");
            var projectFullPath = cps.ProjectFullPath;
            var pri             = cps.Builder
                                  .WithTargetFrameworkInfo(
                new VsTargetFrameworkInfo(
                    "netcoreapp1.0",
                    Enumerable.Empty <IVsReferenceItem>(),
                    Enumerable.Empty <IVsReferenceItem>(),
                    new[] { new VsProjectProperty("RestorePackagesPath", restorePackagesPath),
                            new VsProjectProperty("RestoreSources", restoreSources),
                            new VsProjectProperty("RestoreFallbackFolders", fallbackFolders) }))
                                  .Build();

            // Act
            var actualRestoreSpec = await CaptureNominateResultAsync(projectFullPath, cps.ProjectRestoreInfo);

            // Assert
            SpecValidationUtility.ValidateDependencySpec(actualRestoreSpec);

            var actualProjectSpec = actualRestoreSpec.GetProjectSpec(projectFullPath);

            Assert.NotNull(actualProjectSpec);
            Assert.Equal(restorePackagesPath, actualProjectSpec.RestoreMetadata.PackagesPath);

            var specSources     = actualProjectSpec.RestoreMetadata.Sources?.Select(e => e.Source);
            var expectedSources = MSBuildStringUtility.Split(restoreSources).Any(e => StringComparer.OrdinalIgnoreCase.Equals("clear", e)) ? new string[] { "Clear" } : MSBuildStringUtility.Split(restoreSources);

            Assert.True(Enumerable.SequenceEqual(expectedSources.OrderBy(t => t), specSources.OrderBy(t => t)));

            var specFallback     = actualProjectSpec.RestoreMetadata.FallbackFolders;
            var expectedFallback = MSBuildStringUtility.Split(fallbackFolders).Any(e => StringComparer.OrdinalIgnoreCase.Equals("clear", e)) ? new string[] { "Clear" } : MSBuildStringUtility.Split(fallbackFolders);

            Assert.True(Enumerable.SequenceEqual(expectedFallback.OrderBy(t => t), specFallback.OrderBy(t => t)));
        }
Esempio n. 24
0
        public async Task <string[]> GetProjectTypeGuidsAsync()
        {
            if (!IsDeferred)
            {
                return(VsHierarchyUtility.GetProjectTypeGuids(Project));
            }
            else
            {
                // Get ProjectTypeGuids from msbuild property, if it doesn't exist, fall back to projectTypeGuid.
                var projectTypeGuids = await BuildProperties.GetPropertyValueAsync(ProjectBuildProperties.ProjectTypeGuids);

                if (!string.IsNullOrEmpty(projectTypeGuids))
                {
                    return(MSBuildStringUtility.Split(projectTypeGuids));
                }

                if (!string.IsNullOrEmpty(_projectTypeGuid))
                {
                    return(new string[] { _projectTypeGuid });
                }

                return(Array.Empty <string>());
            }
        }
Esempio n. 25
0
        // The targetpaths returned from this function contain the directory in the nuget package where the file would go to. The filename is added later on to the target path.
        // whether or not the filename is added later on is dependent upon the fact that does the targetpath resolved here ends with a directory separator char or not.
        private IEnumerable <ContentMetadata> GetContentMetadata(IMSBuildItem packageFile, string sourcePath,
                                                                 PackArgs packArgs, string[] contentTargetFolders)
        {
            var targetPaths = contentTargetFolders
                              .Select(PathUtility.EnsureTrailingSlash)
                              .ToList();

            var isPackagePathSpecified = packageFile.Properties.Contains("PackagePath");

            // if user specified a PackagePath, then use that. Look for any ** which are indicated by the RecrusiveDir metadata in msbuild.
            if (isPackagePathSpecified)
            {
                // The rule here is that if the PackagePath is an empty string, then we add the file to the root of the package.
                // Instead if it is a ';' delimited string, then the user needs to specify a '\' to indicate that the file should go to the root of the package.

                var packagePathString = packageFile.GetProperty("PackagePath");
                targetPaths = packagePathString == null
                    ? new string[] { string.Empty }.ToList()
                    : MSBuildStringUtility.Split(packagePathString)
                .Distinct()
                .ToList();

                var recursiveDir = packageFile.GetProperty("RecursiveDir");
                // The below NuGetRecursiveDir workaround needs to be done due to msbuild bug https://github.com/Microsoft/msbuild/issues/3121
                recursiveDir = string.IsNullOrEmpty(recursiveDir) ? packageFile.GetProperty("NuGetRecursiveDir") : recursiveDir;
                if (!string.IsNullOrEmpty(recursiveDir))
                {
                    var newTargetPaths = new List <string>();
                    var fileName       = Path.GetFileName(sourcePath);
                    foreach (var targetPath in targetPaths)
                    {
                        newTargetPaths.Add(PathUtility.GetStringComparerBasedOnOS().
                                           Compare(Path.GetExtension(fileName),
                                                   Path.GetExtension(targetPath)) == 0 &&
                                           !string.IsNullOrEmpty(Path.GetExtension(fileName))
                                ? targetPath
                                : Path.Combine(targetPath, recursiveDir));
                    }

                    targetPaths = newTargetPaths;
                }
            }

            var buildActionString = packageFile.GetProperty("BuildAction");
            var buildAction       = BuildAction.Parse(string.IsNullOrEmpty(buildActionString) ? "None" : buildActionString);

            // TODO: Do the work to get the right language of the project, tracked via https://github.com/NuGet/Home/issues/4100
            var language = buildAction.Equals(BuildAction.Compile) ? "cs" : "any";


            var setOfTargetPaths = new HashSet <string>(targetPaths, PathUtility.GetStringComparerBasedOnOS());

            // If package path wasn't specified, then we expand the "contentFiles" value we
            // got from ContentTargetFolders and expand it to contentFiles/any/<TFM>/
            if (!isPackagePathSpecified)
            {
                if (setOfTargetPaths.Remove("contentFiles" + Path.DirectorySeparatorChar) ||
                    setOfTargetPaths.Remove("contentFiles"))
                {
                    foreach (var framework in packArgs.PackTargetArgs.TargetFrameworks)
                    {
                        setOfTargetPaths.Add(PathUtility.EnsureTrailingSlash(
                                                 Path.Combine("contentFiles", language, framework.GetShortFolderName()
                                                              )));
                    }
                }
            }

            // this  if condition means there is no package path provided, file is within the project directory
            // and the target path should preserve this relative directory structure.
            // This case would be something like :
            // <Content Include= "folderA\folderB\abc.txt">
            // Since the package path wasn't specified, we will add this to the package paths obtained via ContentTargetFolders and preserve
            // relative directory structure
            if (!isPackagePathSpecified &&
                sourcePath.StartsWith(packArgs.CurrentDirectory, StringComparison.CurrentCultureIgnoreCase) &&
                !Path.GetFileName(sourcePath)
                .Equals(packageFile.GetProperty(IdentityProperty), StringComparison.CurrentCultureIgnoreCase))
            {
                var newTargetPaths = new List <string>();
                var identity       = packageFile.GetProperty(IdentityProperty);

                // Identity can be a rooted absolute path too, in which case find the path relative to the current directory
                if (Path.IsPathRooted(identity))
                {
                    identity = PathUtility.GetRelativePath(PathUtility.EnsureTrailingSlash(packArgs.CurrentDirectory), identity);
                    identity = Path.GetDirectoryName(identity);
                }

                // If identity is not a rooted path, then it is a relative path to the project directory
                else if (identity.EndsWith(Path.GetFileName(sourcePath), StringComparison.CurrentCultureIgnoreCase))
                {
                    identity = Path.GetDirectoryName(identity);
                }

                foreach (var targetPath in setOfTargetPaths)
                {
                    var newTargetPath = Path.Combine(targetPath, identity);
                    // We need to do this because evaluated identity in the above line of code can be an empty string
                    // in the case when the original identity string was the absolute path to a file in project directory, and is in
                    // the same directory as the csproj file.
                    newTargetPath = PathUtility.EnsureTrailingSlash(newTargetPath);
                    newTargetPaths.Add(newTargetPath);
                }
                setOfTargetPaths = new HashSet <string>(newTargetPaths, PathUtility.GetStringComparerBasedOnOS());
            }

            // we take the final set of evaluated target paths and append the file name to it if not
            // already done. we check whether the extension of the target path is the same as the extension
            // of the source path and add the filename accordingly.
            var totalSetOfTargetPaths = new List <string>();

            foreach (var targetPath in setOfTargetPaths)
            {
                var currentPath = targetPath;
                var fileName    = Path.GetFileName(sourcePath);
                if (string.IsNullOrEmpty(Path.GetExtension(fileName)) ||
                    !Path.GetExtension(fileName)
                    .Equals(Path.GetExtension(targetPath), StringComparison.OrdinalIgnoreCase))
                {
                    currentPath = Path.Combine(targetPath, fileName);
                }
                totalSetOfTargetPaths.Add(currentPath);
            }

            return(totalSetOfTargetPaths.Select(target => new ContentMetadata()
            {
                BuildAction = buildAction.Value,
                Source = sourcePath,
                Target = target,
                CopyToOutput = packageFile.GetProperty("PackageCopyToOutput"),
                Flatten = packageFile.GetProperty("PackageFlatten")
            }));
        }
Esempio n. 26
0
        public async Task NominateProjectAsync_WithRestoreAdditionalSourcesAndFallbackFolders(string restoreSources, string restoreAdditionalProjectSources, string restoreFallbackFolders, string restoreAdditionalFallbackFolders)
        {
            var cps = NewCpsProject(@"{ }");
            var pri = cps.Builder
                      .WithTool("Foo.Test", "2.0.0")
                      .WithTargetFrameworkInfo(
                new VsTargetFrameworkInfo(
                    "netcoreapp2.0",
                    Enumerable.Empty <IVsReferenceItem>(),
                    Enumerable.Empty <IVsReferenceItem>(),
                    new[] { new VsProjectProperty("RestoreSources", restoreSources),
                            new VsProjectProperty("RestoreFallbackFolders", restoreFallbackFolders),
                            new VsProjectProperty("RestoreAdditionalProjectSources", restoreAdditionalProjectSources),
                            new VsProjectProperty("RestoreAdditionalProjectFallbackFolders", restoreAdditionalFallbackFolders) }))
                      .Build();
            var projectFullPath = cps.ProjectFullPath;

            // Act
            var actualRestoreSpec = await CaptureNominateResultAsync(projectFullPath, pri);

            // Assert
            SpecValidationUtility.ValidateDependencySpec(actualRestoreSpec);

            var actualProjectSpec = actualRestoreSpec.GetProjectSpec(projectFullPath);

            Assert.NotNull(actualProjectSpec);

            var specSources = actualProjectSpec.RestoreMetadata.Sources?.Select(e => e.Source);

            var expectedSources =
                (MSBuildStringUtility.Split(restoreSources).Any(e => StringComparer.OrdinalIgnoreCase.Equals("clear", e)) ?
                 new string[] { "Clear" } :
                 MSBuildStringUtility.Split(restoreSources)).
                Concat(
                    restoreAdditionalProjectSources != null ?
                    new List <string>()
            {
                VSRestoreSettingsUtilities.AdditionalValue
            }.Concat(MSBuildStringUtility.Split(restoreAdditionalProjectSources)):
                    new string[] { }
                    );

            Assert.True(Enumerable.SequenceEqual(expectedSources.OrderBy(t => t), specSources.OrderBy(t => t)));

            var specFallback = actualProjectSpec.RestoreMetadata.FallbackFolders;

            var expectedFallback =
                (MSBuildStringUtility.Split(restoreFallbackFolders).Any(e => StringComparer.OrdinalIgnoreCase.Equals("clear", e)) ?
                 new string[] { "Clear" } :
                 MSBuildStringUtility.Split(restoreFallbackFolders)).
                Concat(
                    restoreAdditionalFallbackFolders != null ?
                    new List <string>()
            {
                VSRestoreSettingsUtilities.AdditionalValue
            }.Concat(MSBuildStringUtility.Split(restoreAdditionalFallbackFolders)) :
                    new string[] { }
                    );

            Assert.True(
                Enumerable.SequenceEqual(expectedFallback.OrderBy(t => t), specFallback.OrderBy(t => t)),
                "expected: " + string.Join(",", expectedFallback.ToArray()) + "\nactual: " + string.Join(",", specFallback.ToArray()));
        }
Esempio n. 27
0
        /// <summary>
        /// Splits the value of the specified property and returns an array if the property has a value, otherwise returns <code>null</code>.
        /// </summary>
        /// <param name="item">The <see cref="IMSBuildItem" /> to get the property value from.</param>
        /// <param name="name">The name of the property to get the value of and split.</param>
        /// <returns>A <see cref="T:string[]" /> containing the split value of the property if the property had a value, otherwise <code>null</code>.</returns>
        public static string[] SplitGlobalPropertyValueOrNull(this IMSBuildProject item, string name)
        {
            string value = item.GetGlobalProperty(name);

            return(value == null ? null : MSBuildStringUtility.Split(value));
        }
        public async Task GetPackageSpecsAsync_ReadSettingsWithFullPaths(string restorePackagesPath, string sources, string fallbackFolders)
        {
            // Arrange
            using (var testDirectory = TestDirectory.Create())
            {
                var projectAdapter = CreateProjectAdapter(testDirectory);
                Mock.Get(projectAdapter)
                .SetupGet(x => x.RestorePackagesPath)
                .Returns(restorePackagesPath);

                Mock.Get(projectAdapter)
                .SetupGet(x => x.RestoreSources)
                .Returns(sources);

                Mock.Get(projectAdapter)
                .SetupGet(x => x.RestoreFallbackFolders)
                .Returns(fallbackFolders);

                var projectServices = new TestProjectSystemServices();

                var testProject = new LegacyPackageReferenceProject(
                    projectAdapter,
                    Guid.NewGuid().ToString(),
                    projectServices,
                    _threadingService);

                var settings = NullSettings.Instance;
                var testDependencyGraphCacheContext = new DependencyGraphCacheContext(NullLogger.Instance, settings);

                await _threadingService.JoinableTaskFactory.SwitchToMainThreadAsync();

                // Act
                var packageSpecs = await testProject.GetPackageSpecsAsync(testDependencyGraphCacheContext);

                // Assert
                Assert.NotNull(packageSpecs);
                var actualRestoreSpec = packageSpecs.Single();
                SpecValidationUtility.ValidateProjectSpec(actualRestoreSpec);

                // Assert packagespath
                Assert.Equal(restorePackagesPath != null ? restorePackagesPath : SettingsUtility.GetGlobalPackagesFolder(settings), actualRestoreSpec.RestoreMetadata.PackagesPath);

                // assert sources
                var specSources     = actualRestoreSpec.RestoreMetadata.Sources.Select(e => e.Source);
                var expectedSources = sources != null?MSBuildStringUtility.Split(sources) : SettingsUtility.GetEnabledSources(settings).Select(e => e.Source);

                Assert.True(Enumerable.SequenceEqual(expectedSources.OrderBy(t => t), specSources.OrderBy(t => t)));

                // assert fallbackfolders
                var specFallback    = actualRestoreSpec.RestoreMetadata.FallbackFolders;
                var expectedFolders = fallbackFolders != null?MSBuildStringUtility.Split(fallbackFolders) : SettingsUtility.GetFallbackPackageFolders(settings);

                Assert.True(Enumerable.SequenceEqual(expectedFolders.OrderBy(t => t), specFallback.OrderBy(t => t)));

                // Verify
                Mock.Get(projectAdapter)
                .Verify(x => x.RestorePackagesPath, Times.Once);
                Mock.Get(projectAdapter)
                .Verify(x => x.RestoreSources, Times.Once);
                Mock.Get(projectAdapter)
                .Verify(x => x.RestoreFallbackFolders, Times.Once);
            }
        }
        /// <summary>
        /// Gets the restore metadata and target framework information for the specified project.
        /// </summary>
        /// <param name="project">An <see cref="IMSBuildProject" /> representing the project.</param>
        /// <param name="projectsByTargetFramework">A <see cref="IReadOnlyDictionary{NuGetFramework,IMSBuildProject}" /> containing the inner nodes by target framework.</param>
        /// <param name="settings">The <see cref="ISettings" /> of the specified project.</param>
        /// <returns>A <see cref="Tuple" /> containing the <see cref="ProjectRestoreMetadata" /> and <see cref="List{TargetFrameworkInformation}" /> for the specified project.</returns>
        private (ProjectRestoreMetadata RestoreMetadata, List <TargetFrameworkInformation> TargetFrameworkInfos) GetProjectRestoreMetadataAndTargetFrameworkInformation(IMSBuildProject project, IReadOnlyDictionary <NuGetFramework, IMSBuildProject> projectsByTargetFramework, ISettings settings)
        {
            var projectName = GetProjectName(project);

            var outputPath = GetRestoreOutputPath(project);

            var targetFrameworkInfos = GetTargetFrameworkInfos(projectsByTargetFramework);

            var projectStyleResult = BuildTasksUtility.GetProjectRestoreStyle(
                restoreProjectStyle: project.GetProperty("RestoreProjectStyle"),
                hasPackageReferenceItems: targetFrameworkInfos.Any(i => i.Dependencies.Any()),
                projectJsonPath: project.GetProperty("_CurrentProjectJsonPath"),
                projectDirectory: project.Directory,
                projectName: project.GetProperty("MSBuildProjectName"),
                log: MSBuildLogger);

            var projectStyle = projectStyleResult.ProjectStyle;

            var innerNodes = projectsByTargetFramework.Values.ToList();

            ProjectRestoreMetadata restoreMetadata;

            if (projectStyle == ProjectStyle.PackagesConfig)
            {
                restoreMetadata = new PackagesConfigProjectRestoreMetadata
                {
                    PackagesConfigPath = projectStyleResult.PackagesConfigFilePath,
                    RepositoryPath     = GetRepositoryPath(project, settings)
                };
            }
            else
            {
                restoreMetadata = new ProjectRestoreMetadata
                {
                    CrossTargeting  = (projectStyle == ProjectStyle.PackageReference || projectStyle == ProjectStyle.DotnetToolReference) && projectsByTargetFramework.Count > 1,
                    FallbackFolders = BuildTasksUtility.GetFallbackFolders(
                        project.Directory,
                        project.SplitPropertyValueOrNull("RestoreFallbackFolders"),
                        project.SplitPropertyValueOrNull("RestoreFallbackFoldersOverride"),
                        innerNodes.SelectMany(i => MSBuildStringUtility.Split(i.GetProperty("RestoreAdditionalProjectFallbackFolders"))),
                        innerNodes.SelectMany(i => MSBuildStringUtility.Split(i.GetProperty("RestoreAdditionalProjectFallbackFoldersExcludes"))),
                        settings),
                    SkipContentFileWrite  = IsLegacyProject(project),
                    ValidateRuntimeAssets = project.IsPropertyTrue("ValidateRuntimeIdentifierCompatibility")
                };
            }

            restoreMetadata.CacheFilePath                = NoOpRestoreUtilities.GetProjectCacheFilePath(outputPath, project.FullPath);
            restoreMetadata.ConfigFilePaths              = settings.GetConfigFilePaths();
            restoreMetadata.OutputPath                   = outputPath;
            restoreMetadata.OriginalTargetFrameworks     = GetOriginalTargetFrameworks(project, projectsByTargetFramework.Keys.ToList());
            restoreMetadata.PackagesPath                 = GetPackagesPath(project, settings);
            restoreMetadata.ProjectName                  = projectName;
            restoreMetadata.ProjectPath                  = project.FullPath;
            restoreMetadata.ProjectStyle                 = projectStyle;
            restoreMetadata.ProjectUniqueName            = project.FullPath;
            restoreMetadata.ProjectWideWarningProperties = WarningProperties.GetWarningProperties(project.GetProperty("TreatWarningsAsErrors"), project.GetProperty("WarningsAsErrors"), project.GetProperty("NoWarn"));
            restoreMetadata.RestoreLockProperties        = new RestoreLockProperties(project.GetProperty("RestorePackagesWithLockFile"), project.GetProperty("NuGetLockFilePath"), project.IsPropertyTrue("RestoreLockedMode"));
            restoreMetadata.Sources          = GetSources(project, innerNodes, settings);
            restoreMetadata.TargetFrameworks = GetProjectRestoreMetadataFrameworkInfos(projectsByTargetFramework);

            return(restoreMetadata, targetFrameworkInfos);
        }
Esempio n. 30
0
        private async Task <bool> ExecuteAsync(Common.ILogger log)
        {
            if (RestoreGraphItems.Length < 1)
            {
                log.LogWarning(Strings.NoProjectsProvidedToTask);
                return(true);
            }

            // Set user agent and connection settings.
            ConfigureProtocol();

            // Convert to the internal wrapper
            var wrappedItems = RestoreGraphItems.Select(MSBuildUtility.WrapMSBuildItem);

            //var graphLines = RestoreGraphItems;
            var providerCache = new RestoreCommandProvidersCache();

            using (var cacheContext = new SourceCacheContext())
            {
                cacheContext.NoCache             = RestoreNoCache;
                cacheContext.IgnoreFailedSources = RestoreIgnoreFailedSources;

                // Pre-loaded request provider containing the graph file
                var providers = new List <IPreLoadedRestoreRequestProvider>();

                var dgFile = MSBuildRestoreUtility.GetDependencySpec(wrappedItems);

                if (dgFile.Restore.Count < 1)
                {
                    // Restore will fail if given no inputs, but here we should skip it and provide a friendly message.
                    log.LogMinimal(Strings.NoProjectsToRestore);
                    return(true);
                }

                // Add all child projects
                if (RestoreRecursive)
                {
                    BuildTasksUtility.AddAllProjectsForRestore(dgFile);
                }

                providers.Add(new DependencyGraphSpecRequestProvider(providerCache, dgFile));

                var defaultSettings = Settings.LoadDefaultSettings(root: null, configFileName: null, machineWideSettings: null);
                var sourceProvider  = new CachingSourceProvider(new PackageSourceProvider(defaultSettings));

                var restoreContext = new RestoreArgs()
                {
                    CacheContext         = cacheContext,
                    LockFileVersion      = LockFileFormat.Version,
                    ConfigFile           = MSBuildStringUtility.TrimAndGetNullForEmpty(RestoreConfigFile),
                    DisableParallel      = RestoreDisableParallel,
                    GlobalPackagesFolder = RestorePackagesPath,
                    Log = log,
                    MachineWideSettings       = new XPlatMachineWideSetting(),
                    PreLoadedRequestProviders = providers,
                    CachingSourceProvider     = sourceProvider,
                    AllowNoOp             = !RestoreForce,
                    HideWarningsAndErrors = HideWarningsAndErrors
                };

                if (!string.IsNullOrEmpty(RestoreSources))
                {
                    var sources = MSBuildStringUtility.Split(RestoreSources);
                    restoreContext.Sources.AddRange(sources);
                }

                if (restoreContext.DisableParallel)
                {
                    HttpSourceResourceProvider.Throttle = SemaphoreSlimThrottle.CreateBinarySemaphore();
                }

                _cts.Token.ThrowIfCancellationRequested();

                var restoreSummaries = await RestoreRunner.RunAsync(restoreContext, _cts.Token);

                // Summary
                RestoreSummary.Log(log, restoreSummaries);

                return(restoreSummaries.All(x => x.Success));
            }
        }