public static Package GetPackage(string nupkgPath) { var result = new Package(); using (var packageFile = File.Open(nupkgPath, FileMode.Open, FileAccess.Read)) { using (var packageReader = new PackageArchiveReader(packageFile)) { var manifestReader = new NuspecReader(packageReader.GetNuspec()); result.Authors = manifestReader.GetAuthors(); result.DependencySets = manifestReader.GetDependencyGroups(); result.Description = manifestReader.GetDescription(); result.Id = manifestReader.GetIdentity().Id; result.LicenseUrl = manifestReader.GetLicenseUrl(); result.ProjectUrl = manifestReader.GetProjectUrl(); result.Summary = manifestReader.GetSummary(); result.Version = manifestReader.GetIdentity().Version; result.RequireLicenseAcceptance = manifestReader.GetRequireLicenseAcceptance(); result.Files = packageReader.GetFiles() .Where(x => x != "[Content_Types].xml" && x != "_rels/.rels" && !x.EndsWith(".nuspec") && !x.EndsWith(".psmdcp")) .Select(x => x.Replace("/", "\\")) .OrderBy(x => x).ToList(); } } return(result); }
/// <summary> /// Create a PackageInput for Add. /// </summary> public PackageInput(string packagePath, bool isSymbolsPackage, NuspecReader nuspecReader) { PackagePath = packagePath ?? throw new ArgumentNullException(nameof(packagePath)); IsSymbolsPackage = isSymbolsPackage; Nuspec = nuspecReader ?? throw new ArgumentNullException(nameof(nuspecReader)); Identity = nuspecReader.GetIdentity(); }
/// <summary> /// Read dependency info from a nuspec. /// </summary> /// <remarks>This also verifies minClientVersion.</remarks> protected static FindPackageByIdDependencyInfo GetDependencyInfo(NuspecReader reader) { // Since this is the first place a package is read after selecting it as the best version // check the minClientVersion here to verify we are okay to read this package. MinClientVersionUtility.VerifyMinClientVersion(reader); // Create dependency info return(new FindPackageByIdDependencyInfo( reader.GetIdentity(), reader.GetDependencyGroups(), reader.GetFrameworkReferenceGroups())); }
/// <summary> /// Determines if a package is installed based on the provided package save mode. /// </summary> /// <param name="packageIdentity">A package identity.</param> /// <param name="packageSaveMode">A package save mode.</param> /// <returns>A flag indicating whether or not the package is installed.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="packageIdentity" /> /// is <c>null</c>.</exception> public bool PackageExists(PackageIdentity packageIdentity, PackageSaveMode packageSaveMode) { if (packageIdentity == null) { throw new ArgumentNullException(nameof(packageIdentity)); } var nupkgPath = GetInstalledPackageFilePath(packageIdentity); var nuspecPath = GetInstalledManifestFilePath(packageIdentity); var packageExists = !string.IsNullOrEmpty(nupkgPath); var manifestExists = !string.IsNullOrEmpty(nuspecPath); // When using -ExcludeVersion check that the actual package version matches. if (!PackagePathResolver.UseSideBySidePaths) { if (packageExists) { using (var reader = new PackageArchiveReader(nupkgPath)) { packageExists = packageIdentity.Equals(reader.NuspecReader.GetIdentity()); } } if (manifestExists) { var reader = new NuspecReader(nuspecPath); packageExists = packageIdentity.Equals(reader.GetIdentity()); } } if (!packageExists) { packageExists |= !string.IsNullOrEmpty(GetPackageDownloadMarkerFilePath(packageIdentity)); } // A package must have either a nupkg or a nuspec to be valid var result = packageExists || manifestExists; // Verify nupkg present if specified if ((packageSaveMode & PackageSaveMode.Nupkg) == PackageSaveMode.Nupkg) { result &= packageExists; } // Verify nuspec present if specified if ((packageSaveMode & PackageSaveMode.Nuspec) == PackageSaveMode.Nuspec) { result &= manifestExists; } return(result); }
private IReadOnlyList <LocalPackageInfo> GetPackageInfosCore(string id, ILogger logger) { var result = new List <LocalPackageInfo>(); // packages\{packageId}.{version}.nupkg var nupkgFiles = LocalFolderUtility.GetNupkgsFromFlatFolder(_source, logger) .Where(path => LocalFolderUtility.IsPossiblePackageMatch(path, id)); foreach (var nupkgInfo in nupkgFiles) { using (var stream = nupkgInfo.OpenRead()) using (var packageReader = new PackageArchiveReader(stream)) { NuspecReader reader; try { reader = new NuspecReader(packageReader.GetNuspec()); } catch (XmlException ex) { var message = string.Format(CultureInfo.CurrentCulture, Strings.Protocol_PackageMetadataError, nupkgInfo.Name, _source); throw new FatalProtocolException(message, ex); } catch (PackagingException ex) { var message = string.Format(CultureInfo.CurrentCulture, Strings.Protocol_PackageMetadataError, nupkgInfo.Name, _source); throw new FatalProtocolException(message, ex); } var identity = reader.GetIdentity(); if (string.Equals(identity.Id, id, StringComparison.OrdinalIgnoreCase)) { var cachePackage = new LocalPackageInfo( identity, nupkgInfo.FullName, nupkgInfo.LastWriteTimeUtc, new Lazy <NuspecReader>(() => reader), new Func <PackageReaderBase>(() => new PackageArchiveReader(nupkgInfo.FullName)) ); result.Add(cachePackage); } } } return(result); }
bool TryReadPackageIdentity(string packageFile, out PackageIdentity packageIdentity) { packageIdentity = null; try { using (var reader = new PackageArchiveReader(new FileStream(packageFile, FileMode.Open, FileAccess.Read))) { var nuspecReader = new NuspecReader(reader.GetNuspec()); packageIdentity = nuspecReader.GetIdentity(); return(true); } } catch (Exception ex) { log.Warning(ex, "Could not read manifest from '{PackageFile:l}'", packageFile); } return(false); }
/// <summary> /// Determines if a manifest is installed. /// </summary> /// <param name="packageIdentity">A package identity.</param> /// <returns>A flag indicating whether or not the package is installed.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="packageIdentity" /> /// is <c>null</c>.</exception> public bool ManifestExists(PackageIdentity packageIdentity) { if (packageIdentity == null) { throw new ArgumentNullException(nameof(packageIdentity)); } var path = GetInstalledManifestFilePath(packageIdentity); var exists = !string.IsNullOrEmpty(path); if (exists && !PackagePathResolver.UseSideBySidePaths) { var reader = new NuspecReader(path); exists = packageIdentity.Equals(reader.GetIdentity()); } return(exists); }
/// <summary> /// Apply build actions from the nuspec to items from the contentFiles folder. /// </summary> internal static List <LockFileContentFile> GetContentFileGroup( NuspecReader nuspec, List <ContentItemGroup> contentFileGroups) { var results = new List <LockFileContentFile>(contentFileGroups.Count); var rootFolderPathLength = ContentFilesFolderName.Length; // Read the contentFiles section of the nuspec // Read the entries so that the bottom entry has priority var nuspecContentFiles = nuspec.GetContentFiles().ToList(); // Initialize mappings var entryMappings = new Dictionary <string, List <ContentFilesEntry> >(StringComparer.OrdinalIgnoreCase); var languageMappings = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); foreach (var group in contentFileGroups) { var codeLanguage = group.Properties[ManagedCodeConventions.PropertyNames.CodeLanguage] as string; foreach (var item in group.Items) { if (!entryMappings.ContainsKey(item.Path)) { entryMappings.Add(item.Path, new List <ContentFilesEntry>()); languageMappings.Add(item.Path, codeLanguage); } } } // Virtual root for file globbing var rootDirectory = new VirtualFileInfo(VirtualFileProvider.RootDir, isDirectory: true); // Apply all nuspec property mappings to the files returned by content model foreach (var filesEntry in nuspecContentFiles) { // this is validated in the nuspec reader Debug.Assert(filesEntry.Include != null, "invalid contentFiles entry"); // Create a filesystem matcher for globbing patterns var matcher = new Matcher(StringComparison.OrdinalIgnoreCase); matcher.AddInclude(filesEntry.Include); if (filesEntry.Exclude != null) { matcher.AddExclude(filesEntry.Exclude); } // Check each file against the patterns foreach (var file in entryMappings.Keys) { // Remove contentFiles/ from the string Debug.Assert(file.StartsWith(ContentFilesFolderName, StringComparison.OrdinalIgnoreCase), "invalid file path: " + file); // All files should begin with the same root folder if (file.Length > rootFolderPathLength) { var relativePath = file.Substring(rootFolderPathLength, file.Length - rootFolderPathLength); // Check if the nuspec group include/exclude patterns apply to the file var virtualDirectory = new VirtualFileProvider(new List <string>() { relativePath }); var globbingDirectory = new FileProviderGlobbingDirectory( virtualDirectory, fileInfo: rootDirectory, parent: null); // Currently Matcher only returns the file name not the full path, each file must be // check individually. var matchResults = matcher.Execute(globbingDirectory); if (matchResults.Files.Any()) { entryMappings[file].Add(filesEntry); } } } } // Create lock file entries for each item in the contentFiles folder foreach (var file in entryMappings.Keys) { // defaults var action = BuildAction.Parse(PackagingConstants.ContentFilesDefaultBuildAction); var copyToOutput = false; var flatten = false; // _._ is needed for empty codeLanguage groups if (file.EndsWith(PackagingCoreConstants.ForwardSlashEmptyFolder, StringComparison.Ordinal)) { action = BuildAction.None; } else { // apply each entry // entries may not have all the attributes, if a value is null // ignore it and continue using the previous value. foreach (var filesEntry in entryMappings[file]) { if (!string.IsNullOrEmpty(filesEntry.BuildAction)) { action = BuildAction.Parse(filesEntry.BuildAction); } if (filesEntry.CopyToOutput.HasValue) { copyToOutput = filesEntry.CopyToOutput.Value; } if (filesEntry.Flatten.HasValue) { flatten = filesEntry.Flatten.Value; } } } // Add attributes to the lock file item var lockFileItem = new LockFileContentFile(file); // Add the language from the directory path lockFileItem.CodeLanguage = languageMappings[file].ToLowerInvariant(); if (!action.IsKnown) { // Throw an error containing the package identity, invalid action, and file where it occurred. var message = string.Format(CultureInfo.CurrentCulture, Strings.Error_UnknownBuildAction, nuspec.GetIdentity(), action, file); throw new PackagingException(message); } lockFileItem.BuildAction = action; lockFileItem.CopyToOutput = copyToOutput; // Check if this is a .pp transform. If the filename is ".pp" ignore it since it will // have no file name after the transform. var isPP = lockFileItem.Path.EndsWith(".pp", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(Path.GetFileNameWithoutExtension(lockFileItem.Path)); if (copyToOutput) { string destination = null; if (flatten) { destination = Path.GetFileName(lockFileItem.Path); } else { // Find path relative to the TxM // Ex: contentFiles/cs/net45/config/config.xml -> config/config.xml destination = GetContentFileFolderRelativeToFramework(file); } if (isPP) { // Remove .pp from the output file path destination = destination.Substring(0, destination.Length - 3); } lockFileItem.OutputPath = destination; } // Add the pp transform file if one exists if (isPP) { var destination = lockFileItem.Path.Substring(0, lockFileItem.Path.Length - 3); destination = GetContentFileFolderRelativeToFramework(destination); lockFileItem.PPOutputPath = destination; } results.Add(lockFileItem); } return(results); }
private async Task <bool?> CheckPackageExistsAsync( FileInfo nugetPackage, string nugetExePath, ILogger logger, string sourceName) { if (!File.Exists(nugetPackage.FullName)) { logger.WriteError( $"The NuGet package '{nugetPackage}' does not exist"); return(null); } logger.WriteDebug($"Searching for existing NuGet package '{nugetPackage}'"); string packageVersion; string packageId; using (var fs = new FileStream(nugetPackage.FullName, FileMode.Open, FileAccess.Read)) { using (var archive = new ZipArchive(fs)) { ZipArchiveEntry nuspecEntry = archive.Entries.SingleOrDefault( entry => Path.GetExtension(entry.Name) .Equals(".nuspec", StringComparison.InvariantCultureIgnoreCase)); if (nuspecEntry == null) { throw new InvalidOperationException("The nuget package does not contain any nuspec"); } var nuspecReader = new NuspecReader(nuspecEntry.Open()); NuGetVersion nuGetVersion = nuspecReader.GetVersion(); packageVersion = nuGetVersion.ToNormalizedString(); packageId = nuspecReader.GetIdentity().Id; } } SemanticVersion expectedVersion = SemanticVersion.Parse(packageVersion); var packageInfo = new { Id = packageId, Version = expectedVersion }; var args = new List <string> { "list", packageId }; if (!string.IsNullOrWhiteSpace(sourceName)) { logger.WriteVerbose($"Using specific source name '{sourceName}'"); args.Add("-source"); args.Add(sourceName); } args.Add("-verbosity"); args.Add("normal"); if (packageInfo.Version.IsPrerelease) { logger.WriteVerbose($"Package '{nugetPackage.Name}' is pre-release"); args.Add("-prerelease"); } var errorBuilder = new StringBuilder(); var standardBuilder = new List <string>(); string expectedNameAndVersion = $"{packageInfo.Id} {expectedVersion.ToNormalizedString()}"; logger.Write($"Looking for '{expectedNameAndVersion}' package"); ExitCode exitCode = await ProcessRunner.ExecuteAsync( nugetExePath, arguments : args, standardOutLog : (message, prefix) => { standardBuilder.Add(message); logger.Write(message, prefix); }, standardErrorAction : (message, prefix) => { errorBuilder.AppendLine(message); logger.WriteError(message, prefix); }, toolAction : logger.Write, addProcessNameAsLogCategory : true, addProcessRunnerCategory : true); if (!exitCode.IsSuccess) { logger.WriteError($"Could not execute process to check if package '{expectedNameAndVersion}' exists"); return(null); } bool foundSpecificPackage = standardBuilder.Any( line => line.Equals(expectedNameAndVersion, StringComparison.InvariantCultureIgnoreCase)); if (foundSpecificPackage) { logger.Write($"Found existing package id '{expectedNameAndVersion}'"); } else { logger.Write($"Could not find existing package id '{expectedNameAndVersion}'"); } return(foundSpecificPackage); }