/// <summary> /// Gets the packages path for the specified project. /// </summary> /// <param name="project">The <see cref="IMSBuildItem" /> representing the project.</param> /// <param name="settings">The <see cref="ISettings" /> of the project.</param> /// <returns>The full path to the packages directory for the specified project.</returns> internal static string GetPackagesPath(IMSBuildProject project, ISettings settings) { return(RestoreSettingsUtils.GetValue( () => UriUtility.GetAbsolutePath(project.Directory, project.GetProperty("RestorePackagesPathOverride")), () => UriUtility.GetAbsolutePath(project.Directory, project.GetProperty("RestorePackagesPath")), () => SettingsUtility.GetGlobalPackagesFolder(settings))); }
/// <summary> /// Gets the target frameworks for the specified project. /// </summary> /// <param name="project">An <see cref="IMSBuildProject" /> representing the main project.</param> /// <param name="innerNodes">An <see cref="IReadOnlyDictionary{String,IMSBuildProject}" /> representing all inner projects by their target framework.</param> /// <returns></returns> internal static IReadOnlyDictionary <NuGetFramework, IMSBuildProject> GetProjectTargetFrameworks(IMSBuildProject project, IReadOnlyDictionary <string, IMSBuildProject> innerNodes) { // Get the raw list of target frameworks that the project specifies var projectFrameworkStrings = MSBuildProjectFrameworkUtility.GetProjectFrameworkStrings( projectFilePath: project.FullPath, targetFrameworks: project.GetProperty("TargetFrameworks"), targetFramework: project.GetProperty("TargetFramework"), targetFrameworkMoniker: project.GetProperty("TargetFrameworkMoniker"), targetPlatformIdentifier: project.GetProperty("TargetPlatformIdentifier"), targetPlatformVersion: project.GetProperty("TargetPlatformVersion"), targetPlatformMinVersion: project.GetProperty("TargetPlatformMinVersion")).ToList(); var projectTargetFrameworks = new Dictionary <NuGetFramework, IMSBuildProject>(); foreach (var projectTargetFramework in projectFrameworkStrings) { // Attempt to get the corresponding project instance for the target framework. If one is not found, then the project must not target multiple frameworks // and the main project should be used if (!innerNodes.TryGetValue(projectTargetFramework, out IMSBuildProject innerNode)) { innerNode = project; } // Add the target framework and associate it with the project instance to be used for gathering details projectTargetFrameworks[NuGetFramework.Parse(projectTargetFramework)] = innerNode; } return(projectTargetFrameworks); }
/// <summary> /// Gets the package references for the specified project. /// </summary> /// <param name="project">The <see cref="ProjectInstance" /> to get package references for.</param> /// <returns>A <see cref="List{LibraryDependency}" /> containing the package references for the specified project.</returns> internal static List <LibraryDependency> GetPackageReferences(IMSBuildProject project) { // Get the distinct PackageReference items, ignoring duplicates var packageReferenceItems = project.GetItems("PackageReference").Distinct(ProjectItemInstanceEvaluatedIncludeComparer.Instance).ToList(); var libraryDependencies = new List <LibraryDependency>(packageReferenceItems.Count); foreach (var packageReferenceItem in packageReferenceItems) { string version = packageReferenceItem.GetProperty("Version"); libraryDependencies.Add(new LibraryDependency { AutoReferenced = packageReferenceItem.IsPropertyTrue("IsImplicitlyDefined"), GeneratePathProperty = packageReferenceItem.IsPropertyTrue("GeneratePathProperty"), IncludeType = GetLibraryIncludeFlags(packageReferenceItem.GetProperty("IncludeAssets"), LibraryIncludeFlags.All) & ~GetLibraryIncludeFlags(packageReferenceItem.GetProperty("ExcludeAssets"), LibraryIncludeFlags.None), LibraryRange = new LibraryRange( packageReferenceItem.Identity, !string.IsNullOrWhiteSpace(version) ? VersionRange.Parse(version) : VersionRange.All, LibraryDependencyTarget.Package), NoWarn = MSBuildStringUtility.GetNuGetLogCodes(packageReferenceItem.GetProperty("NoWarn")).ToList(), SuppressParent = GetLibraryIncludeFlags(packageReferenceItem.GetProperty("PrivateAssets"), LibraryIncludeFlagUtils.DefaultSuppressParent) }); } return(libraryDependencies); }
/// <summary> /// Gets a <see cref="PackageSpec" /> for the specified project. /// </summary> /// <param name="project">An <see cref="IMSBuildProject" /> object that represents the project.</param> /// <param name="allInnerNodes">An <see cref="IReadOnlyDictionary{String,IMSBuildProject}" /> that represents all inner projects by their target framework.</param> /// <returns></returns> private PackageSpec GetPackageSpec(IMSBuildProject project, IReadOnlyDictionary <string, IMSBuildProject> allInnerNodes) { var settings = RestoreSettingsUtils.ReadSettings( project.GetProperty("RestoreSolutionDirectory"), project.GetProperty("RestoreRootConfigDirectory") ?? project.Directory, UriUtility.GetAbsolutePath(project.Directory, project.GetProperty("RestoreConfigFile")), MachineWideSettingsLazy, _settingsLoadContext); // Get the target frameworks for the project and the project instance for each framework var projectsByTargetFramework = GetProjectTargetFrameworks(project, allInnerNodes); var restoreMetadataAndTargetFrameworkInformation = GetProjectRestoreMetadataAndTargetFrameworkInformation(project, projectsByTargetFramework, settings); var packageSpec = new PackageSpec(restoreMetadataAndTargetFrameworkInformation.TargetFrameworkInfos) { FilePath = project.FullPath, Name = restoreMetadataAndTargetFrameworkInformation.RestoreMetadata.ProjectName, RestoreMetadata = restoreMetadataAndTargetFrameworkInformation.RestoreMetadata, RuntimeGraph = new RuntimeGraph( MSBuildStringUtility.Split($"{project.GetProperty("RuntimeIdentifiers")};{project.GetProperty("RuntimeIdentifier")}") .Concat(projectsByTargetFramework.Values.SelectMany(i => MSBuildStringUtility.Split($"{i.GetProperty("RuntimeIdentifiers")};{i.GetProperty("RuntimeIdentifier")}"))) .Distinct(StringComparer.Ordinal) .Select(rid => new RuntimeDescription(rid)) .ToList(), MSBuildStringUtility.Split(project.GetProperty("RuntimeSupports")) .Distinct(StringComparer.Ordinal) .Select(s => new CompatibilityProfile(s)) .ToList() ), Version = GetProjectVersion(project) }; return(packageSpec); }
/// <summary> /// Gets the project references of the specified project. /// </summary> /// <param name="project">The <see cref="ProjectInstance" /> to get project references for.</param> /// <returns>A <see cref="List{ProjectRestoreReference}" /> containing the project references for the specified project.</returns> internal static List <ProjectRestoreReference> GetProjectReferences(IMSBuildProject project) { // Get the unique list of ProjectReference items that have the ReferenceOutputAssembly metadata set to "true", ignoring duplicates var projectReferenceItems = project.GetItems("ProjectReference") .Where(i => i.IsPropertyTrue("ReferenceOutputAssembly", defaultValue: true)) .Distinct(ProjectItemInstanceEvaluatedIncludeComparer.Instance) .ToList(); var projectReferences = new List <ProjectRestoreReference>(projectReferenceItems.Count); foreach (var projectReferenceItem in projectReferenceItems) { string fullPath = projectReferenceItem.GetProperty("FullPath"); projectReferences.Add(new ProjectRestoreReference { ExcludeAssets = GetLibraryIncludeFlags(projectReferenceItem.GetProperty("ExcludeAssets"), LibraryIncludeFlags.None), IncludeAssets = GetLibraryIncludeFlags(projectReferenceItem.GetProperty("IncludeAssets"), LibraryIncludeFlags.All), PrivateAssets = GetLibraryIncludeFlags(projectReferenceItem.GetProperty("PrivateAssets"), LibraryIncludeFlagUtils.DefaultSuppressParent), ProjectPath = fullPath, ProjectUniqueName = fullPath }); } return(projectReferences); }
public SampleDataCollection(ProjectContext projectContext, IMSBuildProject msBuildProject, IExpressionInformationService expressionInformationService) { this.projectContext = projectContext; this.msBuildProject = msBuildProject; this.expressionInformationService = expressionInformationService; this.sampleDataClrNamespacePrefix = DataSetContext.GetClrNamespacePrefix(DataSetType.SampleDataSet, this.projectContext.RootNamespace); this.dataStoreClrNamespacePrefix = DataSetContext.GetClrNamespacePrefix(DataSetType.DataStoreSet, this.projectContext.RootNamespace); }
public static string GetSafeName(string name, IMSBuildProject msBuildProject, bool fileSystemFriendly) { string identifier = SampleDataNameHelper.NormalizeName(name, fileSystemFriendly); if (string.IsNullOrEmpty(identifier) || !msBuildProject.IsSafeIdentifier(identifier)) { return((string)null); } return(identifier); }
/// <summary> /// Gets the package sources of the specified project. /// </summary> /// <param name="project">An <see cref="IMSBuildItem" /> representing the project..</param> /// <param name="innerNodes">An <see cref="IReadOnlyCollection{IMSBuildItem}" /> containing the inner nodes of the project if its targets multiple frameworks.</param> /// <param name="settings">The <see cref="ISettings" /> of the specified project.</param> /// <returns>A <see cref="List{PackageSource}" /> object containing the packages sources for the specified project.</returns> internal static List <PackageSource> GetSources(IMSBuildProject project, IReadOnlyCollection <IMSBuildProject> innerNodes, ISettings settings) { return(BuildTasksUtility.GetSources( project.Directory, project.SplitPropertyValueOrNull("RestoreSources"), project.SplitPropertyValueOrNull("RestoreSourcesOverride"), innerNodes.SelectMany(i => MSBuildStringUtility.Split(i.GetProperty("RestoreAdditionalProjectSources"))), settings) .Select(i => new PackageSource(i)) .ToList()); }
public static IMSBuildProjectFactory CreateMSBuildProjectFactory(IMSBuildProject project = null) { if (project == null) { project = new Mock<IMSBuildProject>() { DefaultValue = DefaultValue.Mock }.Object; } var factory = new Mock<IMSBuildProjectFactory>(); factory.Setup(f => f.CreateProject(It.IsAny<string>())).Returns(project); return factory.Object; }
public static IMSBuildProjectFactory CreateMSBuildProjectFactory(IMSBuildProject project = null) { if (project == null) { project = new Mock <IMSBuildProject>() { DefaultValue = DefaultValue.Mock }.Object; } var factory = new Mock <IMSBuildProjectFactory>(); factory.Setup(f => f.CreateProject(It.IsAny <string>())).Returns(project); return(factory.Object); }
/// <summary> /// Gets the repository path for the specified project. /// </summary> /// <param name="project">The <see cref="IMSBuildItem" /> representing the project.</param> /// <param name="settings">The <see cref="ISettings" /> of the specified project.</param> /// <returns>The repository path of the specified project.</returns> internal static string GetRepositoryPath(IMSBuildProject project, ISettings settings) { return(RestoreSettingsUtils.GetValue( () => UriUtility.GetAbsolutePath(project.Directory, project.GetProperty("RestoreRepositoryPathOverride")), () => UriUtility.GetAbsolutePath(project.Directory, project.GetProperty("RestoreRepositoryPath")), () => SettingsUtility.GetRepositoryPath(settings), () => { string solutionDir = project.GetProperty("SolutionPath"); solutionDir = string.Equals(solutionDir, "*Undefined*", StringComparison.OrdinalIgnoreCase) ? project.Directory : Path.GetDirectoryName(solutionDir); return UriUtility.GetAbsolutePath(solutionDir, PackagesConfig.PackagesNodeName); })); }
/// <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); }
private static bool IsUniqueAndSafeName(string normalizedName, IMSBuildProject msBuildProject, IEnumerable <string> existingNames, string nameToIgnore, bool fileSystemFriendly) { if (!msBuildProject.IsSafeIdentifier(normalizedName) || fileSystemFriendly && PathHelper.IsDeviceName(normalizedName)) { return(false); } if (normalizedName == nameToIgnore) { return(true); } if (normalizedName == "xmlns") { return(false); } string normalizedName2 = (int)normalizedName[0] == 95 ? normalizedName.Substring(1) : (string)null; return(Enumerable.FirstOrDefault <string>(existingNames, (Func <string, bool>)(name => !(name == nameToIgnore) && (string.Compare(normalizedName, name, StringComparison.OrdinalIgnoreCase) == 0 || normalizedName2 != null && string.Compare(normalizedName2, name, StringComparison.OrdinalIgnoreCase) == 0))) == null); }
/// <summary> /// Gets the original target frameworks for the specified project. /// </summary> /// <param name="project">An <see cref="IMSBuildItem" /> representing the project.</param> /// <param name="frameworks">An <see cref="IReadOnlyCollection{NuGetFrameowrk}" /> object containing the frameworks that were parsed from the outer project.</param> /// <returns>A <see cref="List{String}" /> containing the original target frameworks of the project.</returns> internal static List <string> GetOriginalTargetFrameworks(IMSBuildProject project, IReadOnlyCollection <NuGetFramework> frameworks) { // If the project specified the TargetFrameworks property, just return that list var projectTargetFrameworks = project.SplitPropertyValueOrNull("TargetFrameworks"); if (projectTargetFrameworks != null) { return(projectTargetFrameworks.ToList()); } // If the project did not specify a value for TargetFrameworks, return the short folder name of the frameworks which where parsed via other properties var targetFrameworks = new List <string>(frameworks.Count); foreach (var framework in frameworks) { targetFrameworks.Add(framework.GetShortFolderName()); } return(targetFrameworks); }
/// <summary> /// Gets the name of the specified project. /// </summary> /// <param name="project">The <see cref="IMSBuildItem" /> representing the project.</param> /// <returns>The name of the specified project.</returns> internal static string GetProjectName(IMSBuildProject project) { string packageId = project.GetProperty("PackageId"); if (!string.IsNullOrWhiteSpace(packageId)) { // If the PackageId property was specified, return that return(packageId); } string assemblyName = project.GetProperty("AssemblyName"); if (!string.IsNullOrWhiteSpace(assemblyName)) { // If the AssemblyName property was specified, return that return(assemblyName); } // By default return the MSBuildProjectName which is a built-in property that represents the name of the project file without the file extension return(project.GetProperty("MSBuildProjectName")); }
/// <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)); } } }
public static string GetUniqueName(string name, IMSBuildProject msBuildProject, IEnumerable <string> existingNames, string nameToIgnore, bool fileSystemFriendly) { string str = SampleDataNameHelper.NormalizeName(name, fileSystemFriendly); if (string.IsNullOrEmpty(str) || !msBuildProject.IsSafeIdentifier(str)) { return((string)null); } if (SampleDataNameHelper.IsUniqueAndSafeName(str, msBuildProject, existingNames, nameToIgnore, fileSystemFriendly)) { return(str); } NumberedName numberedName = new NumberedName(str); while (numberedName.Increment()) { string currentName = numberedName.CurrentName; if (SampleDataNameHelper.IsUniqueAndSafeName(currentName, msBuildProject, existingNames, nameToIgnore, fileSystemFriendly)) { return(currentName); } } return((string)null); }
/// <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); }
internal NuGetMsBuildProjectSystem(string projectFilePath, IMSBuildProjectFactory msbuildProjectFactory) : base(Path.GetDirectoryName(projectFilePath)) { project = msbuildProjectFactory.CreateProject(projectFilePath); }
/// <summary> /// Gets the restore output path for the specified project. /// </summary> /// <param name="project">The <see cref="IMSBuildItem" /> representing the project.</param> /// <returns>The full path to the restore output directory for the specified project.</returns> internal static string GetRestoreOutputPath(IMSBuildProject project) { string outputPath = project.GetProperty("RestoreOutputPath") ?? project.GetProperty("MSBuildProjectExtensionsPath"); return(Path.GetFullPath(Path.Combine(project.Directory, outputPath))); }
/// <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)); }