private void BuildSymbolsPackage(string path)
        {
            PackageBuilder symbolsBuilder;

            if (ProjectJsonPathUtilities.IsProjectConfig(path))
            {
                symbolsBuilder = CreatePackageBuilderFromProjectJson(path, _packArgs.GetPropertyValue);

                // Add output files
                AddOutputFiles(symbolsBuilder, includeSymbols: true);
            }
            else
            {
                symbolsBuilder = CreatePackageBuilderFromNuspec(path);
            }

            // remove unnecessary files when building the symbols package
            ExcludeFilesForSymbolPackage(symbolsBuilder.Files);

            if (!symbolsBuilder.Files.Any())
            {
                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Strings.Error_PackageCommandNoFilesForSymbolsPackage, path, Strings.NuGetDocs));
            }

            string outputPath = GetOutputPath(symbolsBuilder, _packArgs, symbols: true);

            InitCommonPackageBuilderProperties(symbolsBuilder);
            BuildPackage(symbolsBuilder, outputPath);
        }
Exemple #2
0
        /// <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, or packages.config file
            var projectFileName = Path.GetFileName(projectFilePath);

            if (IsPackagesConfig(projectFileName))
            {
                // restoring from packages.config or packages.projectname.config file
                packageRestoreInputs.PackagesConfigFiles.Add(projectFilePath);
            }
            else if (projectFileName.EndsWith("proj", StringComparison.OrdinalIgnoreCase))
            {
                packageRestoreInputs.ProjectFiles.Add(projectFilePath);
            }
            else if (projectFileName.EndsWith(".dg", StringComparison.OrdinalIgnoreCase))
            {
                packageRestoreInputs.RestoreV3Context.Inputs.Add(projectFilePath);
            }
            else if (projectFileName.EndsWith(".sln", StringComparison.OrdinalIgnoreCase))
            {
                ProcessSolutionFile(projectFilePath, packageRestoreInputs);
            }
            else if (ProjectJsonPathUtilities.IsProjectConfig(projectFileName))
            {
                // project.json is no longer allowed
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("Error_ProjectJsonNotAllowed"), projectFileName));
            }
            else
            {
                // Not a file we know about. Try to be helpful without response.
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, RestoreRunner.GetInvalidInputErrorMessage(projectFileName), projectFileName));
            }
        }
        /// <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));
            }
        }
        public void ProjectJsonPathUtilities_IsProjectConfig_False(string path)
        {
            // Arrange & Act
            var result = ProjectJsonPathUtilities.IsProjectConfig(ConvertToUnix(path));

            // Assert
            Assert.False(result);
        }
 private static List <string> GetProjectJsonFilesInDirectory(string path)
 {
     return(Directory.GetFiles(path,
                               $"*{ProjectJsonPathUtilities.ProjectConfigFileName}",
                               SearchOption.AllDirectories)
            .Where(file => ProjectJsonPathUtilities.IsProjectConfig(file))
            .ToList());
 }
        //auto-restore project.json files when they're saved
        void FileChanged(object sender, FileEventArgs e)
        {
            if (PackageManagementServices.BackgroundPackageActionRunner.IsRunning)
            {
                return;
            }

            List <DotNetProject> projects = null;

            //collect all the projects with modified project.json files
            foreach (var eventInfo in e)
            {
                if (ProjectJsonPathUtilities.IsProjectConfig(eventInfo.FileName))
                {
                    var directory = eventInfo.FileName.ParentDirectory;
                    foreach (var project in IdeApp.Workspace.GetAllItems <DotNetProject> ().Where(p => p.BaseDirectory == directory))
                    {
                        if (projects == null)
                        {
                            projects = new List <DotNetProject> ();
                        }
                        projects.Add(project);
                    }
                }
            }

            if (projects == null)
            {
                return;
            }

            //check that the projects have the correct backing system for project.json
            RefreshProjectsIfNecessary(projects);

            //queue up in a timeout in case this was kicked off from a command
            GLib.Timeout.Add(0, () => {
                if (projects.Count == 1)
                {
                    var project = projects [0];
                    //check the project is still open
                    if (IdeApp.Workspace.GetAllItems <DotNetProject> ().Any(p => p == project))
                    {
                        RestorePackagesInProjectHandler.Run(projects [0]);
                    }
                }
                else
                {
                    var solution = projects [0].ParentSolution;
                    //check the solution is still open
                    if (IdeApp.Workspace.GetAllItems <Solution> ().Any(s => s == solution))
                    {
                        RestorePackagesHandler.Run(solution);
                    }
                }
                //TODO: handle project.json changing in multiple solutions at once
                return(false);
            });
        }
Exemple #7
0
        public static bool IsProjectJsonFileName(this FilePath filePath)
        {
            if (filePath == null)
            {
                return(false);
            }

            return(ProjectJsonPathUtilities.IsProjectConfig(filePath));
        }
        public Task <bool> Supports(string path)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }

            // True if dir or project.json file
            var result = Directory.Exists(path) ||
                         (File.Exists(path) && ProjectJsonPathUtilities.IsProjectConfig(path));

            return(Task.FromResult(result));
        }
        private static void CreatePart(ZipArchive package, string path, Stream sourceStream)
        {
            if (PackageHelper.IsManifest(path) || ProjectJsonPathUtilities.IsProjectConfig(path))
            {
                return;
            }

            string entryName = CreatePartEntryName(path);

            var entry = package.CreateEntry(entryName, CompressionLevel.Optimal);

            using (var stream = entry.Open())
            {
                sourceStream.CopyTo(stream);
            }
        }
        private PackageArchiveReader BuildPackage(string path)
        {
            string extension = Path.GetExtension(path);

            if (ProjectJsonPathUtilities.IsProjectConfig(path))
            {
                return(BuildFromProjectJson(path));
            }
            else if (extension.Equals(NuGetConstants.ManifestExtension, StringComparison.OrdinalIgnoreCase))
            {
                return(BuildFromNuspec(path));
            }
            else
            {
                return(BuildFromProjectFile(path));
            }
        }
        private static List <string> GetProjectJsonFilesInDirectory(string path)
        {
            try
            {
                return(Directory.GetFiles(
                           path,
                           $"*{ProjectJsonPathUtilities.ProjectConfigFileName}",
                           SearchOption.AllDirectories)
                       .Where(file => ProjectJsonPathUtilities.IsProjectConfig(file))
                       .ToList());
            }
            catch (UnauthorizedAccessException e)
            {
                // Access to a subpath of the directory is denied.
                var resourceMessage = Strings.Error_UnableToLocateRestoreTarget_Because;
                var message         = string.Format(CultureInfo.CurrentCulture, resourceMessage, path);

                throw new InvalidOperationException(message, e);
            }
        }
Exemple #12
0
        public override bool TryGetPackages(string packageConfigPath, PackageRestoreData packageRestoreData, out IEnumerable <PackageIdentityWithPath> packages)
        {
            packages = null;

            // This parser cannot do anything for packages.config or project.json
            //
            if (NuGetPackagesConfigParser.IsPackagesConfigFile(packageConfigPath) || ProjectJsonPathUtilities.IsProjectConfig(packageConfigPath))
            {
                return(false);
            }

            // This parser requires that the restore info file was created
            //
            if (packageRestoreData == null)
            {
                Log.LogMessage("Missing expected assets file directory.  This is typically because the flag generated at $(CBTModuleNuGetAssetsFlagFile) does not exist or is empty.  Ensure the GenerateModuleAssetFlagFile target is running. It may also be because the CBTModules.proj does not import CBT build.props in some fashion.");
                return(false);
            }

            if (!String.Equals("PackageReference", packageRestoreData.RestoreProjectStyle, StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }

            string lockFilePath = Path.Combine(packageRestoreData.RestoreOutputAbsolutePath, LockFileFormat.AssetsFileName);

            if (!File.Exists(lockFilePath))
            {
                throw new FileNotFoundException($"Missing expected NuGet assets file '{lockFilePath}'.  If you are redefining BaseIntermediateOutputPath ensure it is unique per project. ");
            }

            HashSet <string> processedPackages = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            LockFile lockFile = LockFileUtilities.GetLockFile(lockFilePath, NullLogger.Instance);

            string globalPackagesFolder = SettingsUtility.GetGlobalPackagesFolder(NuGetSettings);

            if (String.IsNullOrWhiteSpace(globalPackagesFolder))
            {
                throw new NuGetConfigurationException(@"Unable to determine the NuGet repository path.  This usually defaults to ""%UserProfile%\.nuget\packages"", ""%NUGET_PACKAGES%"", or the ""globalPackagesFolder"" in your NuGet.config.");
            }

            globalPackagesFolder = Path.GetFullPath(globalPackagesFolder);

            if (!Directory.Exists(globalPackagesFolder))
            {
                throw new DirectoryNotFoundException($"The NuGet repository '{globalPackagesFolder}' does not exist.  Ensure that NuGet restored packages to the location specified in your NuGet.config.");
            }

            Log.LogMessage(MessageImportance.Low, $"Using repository path: '{globalPackagesFolder}'");

            VersionFolderPathResolver versionFolderPathResolver = new VersionFolderPathResolver(globalPackagesFolder);

            packages = new List <PackageIdentityWithPath>();

            foreach (RestorePackage package in packageRestoreData.PackageImportOrder)
            {
                // In <PackageReference only one version of a nuGet package will be installed.  That version may not be the one specified in the <PackageReference item.  So we can not match the version specified in the CBTModules.proj with the version actually installed.  If we want to do any such matching it would simply need to result in a build error.
                IEnumerable <PackageDependency> dependencies = lockFile.Targets.First().Libraries.Where(lib => lib.Name.Equals(package.Id, StringComparison.OrdinalIgnoreCase)).Select(lib => lib.Dependencies).SelectMany(p => p.Select(i => i));

                foreach (PackageDependency dependency in dependencies)
                {
                    // In the <PackageReference scenario nuGet will only install one packageId.  If you have two packages that reference different package versions of a third package then it will choose the common highest version and if there is no common version it will error.  If you have two packages listed with two different versions it will choose the first entry and silently not install the other.
                    // If the package is already processed then skip.  If the package is explicitly added then skip to use that order.
                    if (!processedPackages.Contains(dependency.Id, StringComparer.OrdinalIgnoreCase) && !packageRestoreData.PackageImportOrder.Any(pio => pio.Id.Equals(dependency.Id, StringComparison.OrdinalIgnoreCase)))
                    {
                        LockFileLibrary installedPackage = lockFile.Libraries.First(lockPkg => lockPkg.Name.Equals(dependency.Id, StringComparison.OrdinalIgnoreCase));

                        processedPackages.Add(dependency.Id);

                        AddPackage((List <PackageIdentityWithPath>)packages, installedPackage, versionFolderPathResolver);
                    }
                }

                if (!processedPackages.Contains(package.Id))
                {
                    LockFileLibrary installedPackage = lockFile.Libraries.First(lockPkg => lockPkg.Name.Equals(package.Id, StringComparison.OrdinalIgnoreCase));

                    processedPackages.Add(package.Id);

                    AddPackage((List <PackageIdentityWithPath>)packages, installedPackage, versionFolderPathResolver);
                }
            }

            return(true);
        }
        public override bool TryGetPackages(string packageConfigPath, PackageRestoreData packageRestoreData, out IEnumerable <PackageIdentityWithPath> packages)
        {
            packages = null;

            string projectJsonPath;

            if (ProjectJsonPathUtilities.IsProjectConfig(packageConfigPath))
            {
                projectJsonPath = packageConfigPath;
            }
            else
            {
                if (!String.Equals("ProjectJson", packageRestoreData?.RestoreProjectStyle, StringComparison.OrdinalIgnoreCase) || String.IsNullOrWhiteSpace(packageRestoreData?.ProjectJsonPath))
                {
                    return(false);
                }

                projectJsonPath = packageRestoreData.ProjectJsonPath;
            }

            string lockFilePath = ProjectJsonPathUtilities.GetLockFilePath(projectJsonPath);

            if (!File.Exists(lockFilePath))
            {
                throw new FileNotFoundException($"The lock file '{lockFilePath}' does not exist.  Ensure that the restore succeeded and that the lock file was generated.");
            }

            LockFile lockFile = LockFileUtilities.GetLockFile(lockFilePath, NullLogger.Instance);

            string globalPackagesFolder = SettingsUtility.GetGlobalPackagesFolder(NuGetSettings);

            if (String.IsNullOrWhiteSpace(globalPackagesFolder))
            {
                throw new NuGetConfigurationException(@"Unable to determine the NuGet repository path.  This usually defaults to ""%UserProfile%\.nuget\packages"", ""%NUGET_PACKAGES%"", or the ""globalPackagesFolder"" in your NuGet.config.");
            }

            globalPackagesFolder = Path.GetFullPath(globalPackagesFolder);

            if (!Directory.Exists(globalPackagesFolder))
            {
                throw new DirectoryNotFoundException($"The NuGet repository '{globalPackagesFolder}' does not exist.  Ensure that NuGet is restore packages to the location specified in your NuGet.config.");
            }

            Log.LogMessage(MessageImportance.Low, $"Using repository path: '{globalPackagesFolder}'");

            VersionFolderPathResolver versionFolderPathResolver = new VersionFolderPathResolver(globalPackagesFolder);

            packages = lockFile.Libraries.Select(i =>
            {
                string installPath = versionFolderPathResolver.GetInstallPath(i.Name, i.Version);

                if (!String.IsNullOrWhiteSpace(installPath))
                {
                    installPath = Path.GetFullPath(installPath);
                }
                else
                {
                    Log.LogWarning($"The package '{i.Name}' was not found in the repository.");
                }

                return(new PackageIdentityWithPath(i.Name, i.Version, installPath));
            }).Where(i => !String.IsNullOrWhiteSpace(i.FullPath));

            return(true);
        }