public NuGetProject CreateNuGetProject(DotNetProject project, INuGetProjectContext context) { Runtime.AssertMainThread(); var projectSystem = new MonoDevelopMSBuildNuGetProjectSystem(project, context); string projectJsonPath = ProjectJsonPathUtilities.GetProjectConfigPath(project.BaseDirectory, project.Name); if (File.Exists(projectJsonPath)) { return(new BuildIntegratedProjectSystem( projectJsonPath, project.FileName, project, projectSystem, project.Name, settings)); } string baseDirectory = GetBaseDirectory(project); string folderNuGetProjectFullPath = PackagesFolderPathUtility.GetPackagesFolderPath(baseDirectory, settings); string packagesConfigFolderPath = project.BaseDirectory; return(new MSBuildNuGetProject( projectSystem, folderNuGetProjectFullPath, packagesConfigFolderPath)); }
private IVsPathContext GetPathContextForProjectJson( IVsProjectAdapter vsProjectAdapter) { // generate project.lock.json file path from project file var projectFilePath = vsProjectAdapter.FullProjectPath; if (!string.IsNullOrEmpty(projectFilePath)) { var msbuildProjectFile = new FileInfo(projectFilePath); var projectNameFromMSBuildPath = Path.GetFileNameWithoutExtension(msbuildProjectFile.Name); string projectJsonPath = null; if (string.IsNullOrEmpty(projectNameFromMSBuildPath)) { projectJsonPath = Path.Combine(msbuildProjectFile.DirectoryName, ProjectJsonPathUtilities.ProjectConfigFileName); } else { projectJsonPath = ProjectJsonPathUtilities.GetProjectConfigPath( msbuildProjectFile.DirectoryName, projectNameFromMSBuildPath); } if (File.Exists(projectJsonPath)) { var lockFilePath = ProjectJsonPathUtilities.GetLockFilePath(projectJsonPath); return(GetPathContextFromProjectLockFile(lockFilePath)); } } return(null); }
/// <summary> /// Determine if a file is v2 or v3 /// </summary> private void GetInputsFromFile(string projectFilePath, PackageRestoreInputs packageRestoreInputs) { // An argument was passed in. It might be a solution file or directory, // project file, project.json, or packages.config file var projectFileName = Path.GetFileName(projectFilePath); if (ProjectJsonPathUtilities.IsProjectConfig(projectFileName)) { // project.json or projName.project.json packageRestoreInputs.RestoreV3Context.Inputs.Add(projectFilePath); } else if (IsPackagesConfig(projectFileName)) { // restoring from packages.config or packages.projectname.config file packageRestoreInputs.PackagesConfigFiles.Add(projectFilePath); } else if (projectFileName.EndsWith("proj", StringComparison.OrdinalIgnoreCase)) { // For msbuild files find the project.json or packages.config file, // if neither exist skip it var projectName = Path.GetFileNameWithoutExtension(projectFileName); var dir = Path.GetDirectoryName(projectFilePath); var projectJsonPath = ProjectJsonPathUtilities.GetProjectConfigPath(dir, projectName); var packagesConfigPath = GetPackageReferenceFile(projectFilePath); // Check for project.json if (File.Exists(projectJsonPath)) { if (MsBuildUtility.IsMsBuildBasedProject(projectFilePath)) { // Add the project file path if it allows p2ps packageRestoreInputs.RestoreV3Context.Inputs.Add(projectFilePath); } else { // Unknown project type, add the project.json by itself packageRestoreInputs.RestoreV3Context.Inputs.Add(projectJsonPath); } } else if (File.Exists(packagesConfigPath)) { // Check for packages.config, if it exists add it directly packageRestoreInputs.PackagesConfigFiles.Add(packagesConfigPath); } } else if (projectFileName.EndsWith(".dg", StringComparison.OrdinalIgnoreCase)) { packageRestoreInputs.RestoreV3Context.Inputs.Add(projectFilePath); } else if (projectFileName.EndsWith(".sln", StringComparison.OrdinalIgnoreCase)) { ProcessSolutionFile(projectFilePath, packageRestoreInputs); } else { // Not a file we know about. Try to be helpful without response. throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, RestoreRunner.GetInvalidInputErrorMessage(projectFileName), projectFileName)); } }
private void ProcessSolutionFile(string solutionFileFullPath, PackageRestoreInputs restoreInputs) { restoreInputs.DirectoryOfSolutionFile = Path.GetDirectoryName(solutionFileFullPath); // restore packages for the solution var solutionLevelPackagesConfig = Path.Combine( restoreInputs.DirectoryOfSolutionFile, NuGetConstants.NuGetSolutionSettingsFolder, Constants.PackageReferenceFile); if (File.Exists(solutionLevelPackagesConfig)) { restoreInputs.PackagesConfigFiles.Add(solutionLevelPackagesConfig); } var projectFiles = MsBuildUtility.GetAllProjectFileNames(solutionFileFullPath, _msbuildDirectory.Value); foreach (var projectFile in projectFiles) { if (!File.Exists(projectFile)) { var message = string.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("RestoreCommandProjectNotFound"), projectFile); Console.LogWarning(message); continue; } var normalizedProjectFile = Path.GetFullPath(projectFile); // packages.config var packagesConfigFilePath = GetPackageReferenceFile(normalizedProjectFile); // project.json var dir = Path.GetDirectoryName(normalizedProjectFile); var projectName = Path.GetFileNameWithoutExtension(normalizedProjectFile); var projectJsonPath = ProjectJsonPathUtilities.GetProjectConfigPath(dir, projectName); // project.json overrides packages.config if (File.Exists(projectJsonPath)) { // project.json inputs are resolved again against the p2p file // and are matched with the solution there // For known msbuild project types use the project if (MsBuildUtility.IsMsBuildBasedProject(normalizedProjectFile)) { restoreInputs.RestoreV3Context.Inputs.Add(normalizedProjectFile); } else { // For unknown types restore the project.json file without p2ps restoreInputs.RestoreV3Context.Inputs.Add(projectJsonPath); } } else if (File.Exists(packagesConfigFilePath)) { restoreInputs.PackagesConfigFiles.Add(packagesConfigFilePath); } } }
public static async Task MigrateAsync( BuildIntegratedNuGetProject project) { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var dteProjectFullName = project.MSBuildProjectPath; var projectJsonFilePath = ProjectJsonPathUtilities.GetProjectConfigPath(Path.GetDirectoryName(project.MSBuildProjectPath), Path.GetFileNameWithoutExtension(project.MSBuildProjectPath)); if (!File.Exists(projectJsonFilePath)) { throw new FileNotFoundException(string.Format(Strings.Error_FileNotExists, projectJsonFilePath)); } var packageSpec = JsonPackageSpecReader.GetPackageSpec( Path.GetFileNameWithoutExtension(project.MSBuildProjectPath), projectJsonFilePath); if (packageSpec == null) { throw new InvalidOperationException( string.Format(Strings.Error_InvalidJson, projectJsonFilePath)); } await MigrateDependenciesAsync(project, packageSpec); var buildProject = EnvDTEProjectUtility.AsMSBuildEvaluationProject(dteProjectFullName); MigrateRuntimes(packageSpec, buildProject); RemoveProjectJsonReference(buildProject, projectJsonFilePath); await CreateBackupAsync(project, projectJsonFilePath); }
/// <summary> /// Load a project.json for an msbuild project file. /// This allows projectName.project.json for csproj but not for xproj. /// </summary> private PackageSpec GetPackageSpec(string msbuildProjectPath) { PackageSpec result = null; string path = null; var directory = Path.GetDirectoryName(msbuildProjectPath); var projectName = Path.GetFileNameWithoutExtension(msbuildProjectPath); if (msbuildProjectPath.EndsWith(XProjUtility.XProjExtension, StringComparison.OrdinalIgnoreCase)) { // Only project.json is allowed path = Path.Combine( directory, PackageSpec.PackageSpecFileName); } else { // Allow project.json or projectName.project.json path = ProjectJsonPathUtilities.GetProjectConfigPath(directory, projectName); } // Read the file if it exists and is not cached already if (!_projectJsonCache.TryGetValue(path, out result)) { if (File.Exists(path)) { result = JsonPackageSpecReader.GetPackageSpec(projectName, path); } _projectJsonCache.Add(path, result); } return(result); }
static IEnumerable <string> GetPossiblePackagesConfigOrProjectJsonFilePaths(string projectDirectory, string projectName) { yield return(GetNonDefaultProjectPackagesConfigFilePath(projectDirectory, projectName)); yield return(GetDefaultPackagesConfigFilePath(projectDirectory)); yield return(ProjectJsonPathUtilities.GetProjectConfigPath(projectDirectory, projectName)); }
private bool HasProjectJsonFile(string projectFilePath) { // Get possible project.json path var projectFileName = Path.GetFileName(projectFilePath); var projectName = Path.GetFileNameWithoutExtension(projectFileName); var dir = Path.GetDirectoryName(projectFilePath); var projectJsonPath = ProjectJsonPathUtilities.GetProjectConfigPath(dir, projectName); return(File.Exists(projectJsonPath)); }
public NuGetProject CreateNuGetProject(DotNetProject project, INuGetProjectContext context) { Runtime.AssertMainThread(); var nugetAwareProject = project as INuGetAwareProject; if (nugetAwareProject != null) { return(nugetAwareProject.CreateNuGetProject()); } NuGetProject dotNetCoreProject = DotNetCoreNuGetProject.Create(project); if (dotNetCoreProject != null) { return(dotNetCoreProject); } NuGetProject packageReferenceProject = PackageReferenceNuGetProject.Create(project); if (packageReferenceProject != null) { return(packageReferenceProject); } var projectSystem = new MonoDevelopMSBuildNuGetProjectSystem(project, context); string projectJsonPath = ProjectJsonPathUtilities.GetProjectConfigPath(project.BaseDirectory, project.Name); if (File.Exists(projectJsonPath)) { return(new ProjectJsonBuildIntegratedNuGetProject( projectJsonPath, project.FileName, project, settings)); } string baseDirectory = GetBaseDirectory(project); string folderNuGetProjectFullPath = PackagesFolderPathUtility.GetPackagesFolderPath(baseDirectory, settings); string packagesConfigFolderPath = project.BaseDirectory; return(new MonoDevelopMSBuildNuGetProject( projectSystem, folderNuGetProjectFullPath, packagesConfigFolderPath)); }
public void ProjectJsonPathUtilities_GetLockFilePathWithProjectNameOnly() { // Arrange using (var randomProjectFolderPath = TestFileSystemUtility.CreateRandomTestFolder()) { var projNameFile = Path.Combine(randomProjectFolderPath, "abc.project.json"); CreateFile(projNameFile); // Act var path = ProjectJsonPathUtilities.GetProjectConfigPath(randomProjectFolderPath, "abc"); var fileName = Path.GetFileName(path); // Assert Assert.Equal(fileName, "abc.project.json"); } }
public void ProjectJsonPathUtilities_GetLockFilePathWithNoFiles() { // Arrange using (var randomProjectFolderPath = TestFileSystemUtility.CreateRandomTestFolder()) { var expected = Path.Combine(randomProjectFolderPath, "project.json"); // Act var path = ProjectJsonPathUtilities.GetProjectConfigPath(randomProjectFolderPath, "abc"); // Assert Assert.Equal(expected, path); // Clean-up } }
public void ProjectJsonPathUtilities_GetLockFilePathWithProjectJsonOnly() { // Arrange using (var randomProjectFolderPath = TestDirectory.Create()) { var projJsonFile = Path.Combine(randomProjectFolderPath, "project.json"); CreateFile(projJsonFile); // Act var path = ProjectJsonPathUtilities.GetProjectConfigPath(randomProjectFolderPath, "abc"); var fileName = Path.GetFileName(path); // Assert Assert.Equal(fileName, "project.json"); // Clean-up } }
public void Save(string path) { var projectFile = new FileInfo(path); projectFile.Directory.Create(); var xml = GetXML(); File.WriteAllText(path, xml.ToString()); if (ProjectJson != null) { var jsonPath = ProjectJsonPathUtilities.GetProjectConfigPath( projectFile.Directory.FullName, Path.GetFileNameWithoutExtension(ProjectPath)); File.WriteAllText(jsonPath, ProjectJson.ToString()); } }
public static bool ProcessProjectJsonFile(PackageBuilder builder, string basePath, string id, NuGetVersion version, string suffix, Func <string, string> propertyProvider) { if (basePath == null) { return(false); } string path = ProjectJsonPathUtilities.GetProjectConfigPath(basePath, Path.GetFileName(basePath)); if (File.Exists(path)) { using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read)) { LoadProjectJsonFile(builder, path, basePath, id, stream, version, suffix, propertyProvider); } return(true); } return(false); }
public override bool Execute() { var log = new MSBuildLogger(Log); log.LogDebug($"(in) ProjectPath '{ProjectPath}'"); var directory = Path.GetDirectoryName(ProjectPath); var projectName = Path.GetFileNameWithoutExtension(ProjectPath); // Allow project.json or projectName.project.json var path = ProjectJsonPathUtilities.GetProjectConfigPath(directory, projectName); if (File.Exists(path)) { ProjectJsonPath = path; } log.LogDebug($"(out) ProjectJsonPath '{ProjectJsonPath}'"); return(true); }
/// <summary> /// Get only the direct dependencies from a project /// </summary> private DirectReferences GetDirectProjectReferences( EnvDTEProject project, string projectFileFullPath, ExternalProjectReferenceContext context, IVsEnumHierarchyItemsFactory itemsFactory, string rootProjectPath) { var logger = context.Logger; var cache = context.Cache; var result = new DirectReferences(); // Find a project.json in the project // This checks for files on disk to match how BuildIntegratedProjectSystem checks at creation time. // NuGet.exe also uses disk paths and not the project file. var projectName = Path.GetFileNameWithoutExtension(projectFileFullPath); var projectDirectory = Path.GetDirectoryName(projectFileFullPath); // Check for projectName.project.json and project.json string jsonConfigItem = ProjectJsonPathUtilities.GetProjectConfigPath( directoryPath: projectDirectory, projectName: projectName); var hasProjectJson = true; // Verify the file exists, otherwise clear it if (!File.Exists(jsonConfigItem)) { jsonConfigItem = null; hasProjectJson = false; } // Verify ReferenceOutputAssembly var excludedProjects = GetExcludedReferences(project, itemsFactory); var childReferences = new HashSet <string>(StringComparer.Ordinal); var hasMissingReferences = false; // find all references in the project foreach (var childReference in GetProjectReferences(project)) { try { var reference3 = childReference as Reference3; if (reference3 != null && !reference3.Resolved) { // Skip missing references and show a warning hasMissingReferences = true; continue; } // Skip missing references if (childReference.SourceProject != null) { if (EnvDTEProjectUtility.HasUnsupportedProjectCapability(childReference.SourceProject)) { // Skip this shared project continue; } var childName = EnvDTEProjectUtility.GetFullProjectPath(childReference.SourceProject); // Skip projects which have ReferenceOutputAssembly=false if (!string.IsNullOrEmpty(childName) && !excludedProjects.Contains(childName, StringComparer.OrdinalIgnoreCase)) { childReferences.Add(childName); result.ToProcess.Add(new DTEReference(childReference.SourceProject, childName)); } } else if (hasProjectJson) { // SDK references do not have a SourceProject or child references, // but they can contain project.json files, and should be part of the closure // SDKs are not projects, only the project.json name is checked here var possibleSdkPath = childReference.Path; if (!string.IsNullOrEmpty(possibleSdkPath) && !possibleSdkPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) && Directory.Exists(possibleSdkPath)) { var possibleProjectJson = Path.Combine( possibleSdkPath, ProjectJsonPathUtilities.ProjectConfigFileName); if (File.Exists(possibleProjectJson)) { childReferences.Add(possibleProjectJson); // add the sdk to the results here result.Processed.Add(new ExternalProjectReference( possibleProjectJson, childReference.Name, possibleProjectJson, msbuildProjectPath: null, projectReferences: Enumerable.Empty <string>())); } } } } catch (Exception ex) { // Exceptions are expected in some scenarios for native projects, // ignore them and show a warning hasMissingReferences = true; logger.LogDebug(ex.ToString()); Debug.Fail("Unable to find project closure: " + ex.ToString()); } } if (hasMissingReferences) { // Log a warning message once per project // This warning contains only the names of the root project and the project with the // broken reference. Attempting to display more details on the actual reference // that has the problem may lead to another exception being thrown. var warning = string.Format( CultureInfo.CurrentCulture, Strings.Warning_ErrorDuringProjectClosureWalk, projectName, rootProjectPath); logger.LogWarning(warning); } // For the xproj -> xproj -> csproj scenario find all xproj-> xproj references. if (projectFileFullPath.EndsWith(XProjUtility.XProjExtension, StringComparison.OrdinalIgnoreCase)) { // All xproj paths, these are already checked for project.json var xprojFiles = XProjUtility.GetProjectReferences(projectFileFullPath); if (xprojFiles.Count > 0) { var pathToProject = GetPathToDTEProjectLookup(project); foreach (var xProjPath in xprojFiles) { // Only add projects that we can find in the solution, otherwise they will // end up causing failures. If this is an actual failure the resolver will // fail when resolving the dependency from project.json Project xProjDTE; if (pathToProject.TryGetValue(xProjPath, out xProjDTE)) { var xProjFullPath = EnvDTEProjectUtility.GetFullProjectPath(xProjDTE); if (!string.IsNullOrEmpty(xProjFullPath)) { childReferences.Add(xProjFullPath); // Continue walking this project if it has not been walked already result.ToProcess.Add(new DTEReference(xProjDTE, xProjFullPath)); } } } } } // Only set a package spec project name if a package spec exists var packageSpecProjectName = jsonConfigItem == null ? null : projectName; // Add the parent project to the results result.Processed.Add(new ExternalProjectReference( projectFileFullPath, packageSpecProjectName, jsonConfigItem, projectFileFullPath, childReferences)); return(result); }
public bool TryCreateNuGetProject(EnvDTE.Project envDTEProject, ProjectSystemProviderContext context, out NuGetProject result) { if (envDTEProject == null) { throw new ArgumentNullException(nameof(envDTEProject)); } if (context == null) { throw new ArgumentNullException(nameof(context)); } ThreadHelper.ThrowIfNotOnUIThread(); result = null; var msBuildNuGetProjectSystem = MSBuildNuGetProjectSystemFactory.CreateMSBuildNuGetProjectSystem( envDTEProject, context.ProjectContext); var isWebSite = msBuildNuGetProjectSystem is WebSiteProjectSystem; // Web sites cannot have project.json if (!isWebSite) { // Find the project file path var projectFilePath = EnvDTEProjectUtility.GetFullProjectPath(envDTEProject); if (!string.IsNullOrEmpty(projectFilePath)) { var msbuildProjectFile = new FileInfo(projectFilePath); var projectNameFromMSBuildPath = Path.GetFileNameWithoutExtension(msbuildProjectFile.Name); // Treat projects with project.json as build integrated projects // Search for projectName.project.json first, then project.json // If the name cannot be determined, search only for project.json string projectJsonPath = null; if (string.IsNullOrEmpty(projectNameFromMSBuildPath)) { projectJsonPath = Path.Combine(msbuildProjectFile.DirectoryName, ProjectJsonPathUtilities.ProjectConfigFileName); } else { projectJsonPath = ProjectJsonPathUtilities.GetProjectConfigPath(msbuildProjectFile.DirectoryName, projectNameFromMSBuildPath); } if (File.Exists(projectJsonPath)) { result = new ProjectJsonBuildIntegratedProjectSystem( projectJsonPath, msbuildProjectFile.FullName, envDTEProject, EnvDTEProjectUtility.GetCustomUniqueName(envDTEProject)); } } } // Create a normal MSBuild project if no project.json was found if (result == null) { var folderNuGetProjectFullPath = context.PackagesPathFactory(); // Project folder path is the packages config folder path var packagesConfigFolderPath = EnvDTEProjectUtility.GetFullPath(envDTEProject); result = new VSMSBuildNuGetProject( envDTEProject, msBuildNuGetProjectSystem, folderNuGetProjectFullPath, packagesConfigFolderPath); } return(result != null); }
/// <summary> /// Get only the direct dependencies from a project /// </summary> private DirectReferences GetDirectProjectReferences( DotNetProject project, string projectFileFullPath, ExternalProjectReferenceContext context, string rootProjectPath) { var logger = context.Logger; var cache = context.Cache; var result = new DirectReferences(); // Find a project.json in the project // This checks for files on disk to match how BuildIntegratedProjectSystem checks at creation time. // NuGet.exe also uses disk paths and not the project file. var projectName = Path.GetFileNameWithoutExtension(projectFileFullPath); var projectDirectory = Path.GetDirectoryName(projectFileFullPath); // Check for projectName.project.json and project.json string jsonConfigItem = ProjectJsonPathUtilities.GetProjectConfigPath( directoryPath: projectDirectory, projectName: projectName); var hasProjectJson = true; // Verify the file exists, otherwise clear it if (!File.Exists(jsonConfigItem)) { jsonConfigItem = null; hasProjectJson = false; } // Verify ReferenceOutputAssembly var excludedProjects = GetExcludedReferences(project); var childReferences = new HashSet <string> (StringComparer.Ordinal); var hasMissingReferences = false; // find all references in the project foreach (var childReference in project.References) { try { if (!childReference.IsValid) { // Skip missing references and show a warning hasMissingReferences = true; continue; } // Skip missing references DotNetProject sourceProject = null; if (childReference.ReferenceType == ReferenceType.Project) { sourceProject = childReference.ResolveProject(project.ParentSolution) as DotNetProject; } if (sourceProject != null) { string childName = sourceProject.FileName; // Skip projects which have ReferenceOutputAssembly=false if (!string.IsNullOrEmpty(childName) && !excludedProjects.Contains(childName, StringComparer.OrdinalIgnoreCase)) { childReferences.Add(childName); result.ToProcess.Add(new DotNetProjectReference(sourceProject, childName)); } } else if (hasProjectJson) { // SDK references do not have a SourceProject or child references, // but they can contain project.json files, and should be part of the closure // SDKs are not projects, only the project.json name is checked here //var possibleSdkPath = childReference.Path; //if (!string.IsNullOrEmpty (possibleSdkPath) // && !possibleSdkPath.EndsWith (".dll", StringComparison.OrdinalIgnoreCase) // && Directory.Exists(possibleSdkPath)) { // var possibleProjectJson = Path.Combine ( // possibleSdkPath, // ProjectJsonPathUtilities.ProjectConfigFileName); // if (File.Exists (possibleProjectJson)) { // childReferences.Add (possibleProjectJson); // // add the sdk to the results here // result.Processed.Add (new ExternalProjectReference ( // possibleProjectJson, // childReference.Name, // possibleProjectJson, // msbuildProjectPath: null, // projectReferences: Enumerable.Empty<string> ())); // } //} } } catch (Exception ex) { // Exceptions are expected in some scenarios for native projects, // ignore them and show a warning hasMissingReferences = true; logger.LogDebug(ex.Message); LoggingService.LogError("Unable to find project closure.", ex); } } if (hasMissingReferences) { // Log a warning message once per project // This warning contains only the names of the root project and the project with the // broken reference. Attempting to display more details on the actual reference // that has the problem may lead to another exception being thrown. var warning = GettextCatalog.GetString("Failed to resolve all project references for '{0}'. The package restore result for '{1}' may be incomplete.", projectName, rootProjectPath); logger.LogWarning(warning); } // Only set a package spec project name if a package spec exists var packageSpecProjectName = jsonConfigItem == null ? null : projectName; // Add the parent project to the results result.Processed.Add(new ExternalProjectReference( projectFileFullPath, packageSpecProjectName, jsonConfigItem, projectFileFullPath, childReferences)); return(result); }