Example #1
0
        public string Sha256(SnapRelease snapRelease, [NotNull] IPackageCoreReader packageCoreReader, [NotNull] ISnapPack snapPack)
        {
            if (snapRelease == null)
            {
                throw new ArgumentNullException(nameof(snapRelease));
            }
            if (packageCoreReader == null)
            {
                throw new ArgumentNullException(nameof(packageCoreReader));
            }
            if (snapPack == null)
            {
                throw new ArgumentNullException(nameof(snapPack));
            }

            var packageArchiveFiles = packageCoreReader.GetFiles();

            var checksumFiles = GetChecksumFilesForSnapRelease(snapRelease);

            var inputStreams = checksumFiles
                               .Select(checksum => (checksum, targetPath: packageArchiveFiles.SingleOrDefault(targetPath => checksum.NuspecTargetPath == targetPath)))
                               .Select(x =>
            {
                var(checksum, packageArchiveReaderTargetPath) = x;
                if (packageArchiveReaderTargetPath == null)
                {
                    throw new FileNotFoundException($"Unable to find file in nupkg: {snapRelease.Filename}.", checksum.NuspecTargetPath);
                }
                return(checksum, packageCoreReader.GetStream(packageArchiveReaderTargetPath));
            });

            return(Sha256(inputStreams));
        }
        /// <summary>
        /// A package is deemed to be a satellite package if it has a language property set, the id of the package is
        /// of the format [.*].[Language]
        /// and it has at least one dependency with an id that maps to the runtime package .
        /// </summary>
        public static bool IsSatellitePackage(IPackageCoreReader packageReader, out PackageIdentity runtimePackageIdentity, out string packageLanguage)
        {
            // A satellite package has the following properties:
            //     1) A package suffix that matches the package's language, with a dot preceding it
            //     2) A dependency on the package with the same Id minus the language suffix
            //     3) The dependency can be found by Id in the repository (as its path is needed for installation)
            // Example: foo.ja-jp, with a dependency on foo

            var nuspecReader = new NuspecReader(packageReader.GetNuspec());
            var packageId    = nuspecReader.GetId();

            packageLanguage = nuspecReader.GetLanguage();
            string localruntimePackageId = null;

            if (!String.IsNullOrEmpty(packageLanguage)
                &&
                packageId.EndsWith('.' + packageLanguage, StringComparison.OrdinalIgnoreCase))
            {
                // The satellite pack's Id is of the format <Core-Package-Id>.<Language>. Extract the core package id using this.
                // Additionally satellite packages have a strict dependency on the core package
                localruntimePackageId = packageId.Substring(0, packageId.Length - packageLanguage.Length - 1);

                foreach (var group in nuspecReader.GetDependencyGroups())
                {
                    foreach (var dependencyPackage in group.Packages)
                    {
                        if (dependencyPackage.Id.Equals(localruntimePackageId, StringComparison.OrdinalIgnoreCase) &&
                            dependencyPackage.VersionRange != null &&
                            dependencyPackage.VersionRange.MaxVersion == dependencyPackage.VersionRange.MinVersion &&
                            dependencyPackage.VersionRange.IsMaxInclusive &&
                            dependencyPackage.VersionRange.IsMinInclusive)
                        {
                            var runtimePackageVersion = new NuGetVersion(dependencyPackage.VersionRange.MinVersion.ToNormalizedString());
                            runtimePackageIdentity = new PackageIdentity(dependencyPackage.Id, runtimePackageVersion);
                            return(true);
                        }
                    }
                }
            }

            runtimePackageIdentity = null;
            return(false);
        }
        public static string GetNuspecFile(this IPackageCoreReader packageReader)
        {
            // Find all nuspec files in the root folder of the zip.
            var nuspecEntries = packageReader.GetFiles()
                                .Select(f => f.TrimStart('/').Replace('/', Path.DirectorySeparatorChar))
                                .Where(f => f.EndsWith(PackagingCoreConstants.NuspecExtension, StringComparison.OrdinalIgnoreCase))
                                .Where(f => string.Equals(f, Path.GetFileName(f), StringComparison.OrdinalIgnoreCase))
                                .ToArray();

            if (nuspecEntries.Length == 0)
            {
                throw new PackagingException(Strings.MissingNuspec);
            }
            else if (nuspecEntries.Length > 1)
            {
                throw new PackagingException(Strings.MultipleNuspecFiles);
            }

            return(nuspecEntries[0]);
        }
        private static MemoryStream LoadFileFromPackage(IPackageCoreReader package, string filePath)
        {
            try
            {
                var cleanPath = filePath.Replace('/', '\\');
                if (cleanPath.IndexOf('%') > -1)
                {
                    cleanPath = Uri.UnescapeDataString(cleanPath);
                }

                using var fileStream = package.GetStream(cleanPath);
                var decompressedStream = new MemoryStream();
                fileStream.CopyTo(decompressedStream);
                decompressedStream.Position = 0;
                return(decompressedStream);
            }
            catch (FileLoadException e)
            {
                // Note: intentionally discarding the original exception because I want to ensure the following message is displayed in the 'Exceptions' report
                throw new FileLoadException($"An error occured while loading {Path.GetFileName(filePath)} from the Nuget package. {e.Message}");
            }
        }
Example #5
0
        public static Manifest GetManifest(this IPackageCoreReader packageReader)
        {
            using (var stream = packageReader.GetNuspec())
            {
                var manifest = Manifest.ReadFrom(stream, true);
                manifest.Files.AddRange(packageReader.GetFiles()
                                        // Skip the auto-added stuff
                                        .Where(file =>
                                               file != "[Content_Types].xml" &&
                                               file != "_rels/.rels" &&
                                               !file.EndsWith(".nuspec") &&
                                               !file.EndsWith(".psmdcp"))
                                        .Select(file => new ManifestFile
                {
                    // Can't replicate the Source path as it was originally before adding
                    // to the package, so leave it null to avoid false promises in tests.
                    //Source = file.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar),
                    Target = file.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar)
                }));

                return(manifest);
            }
        }
        private (Stream AssemblyStream, Assembly Assembly, MethodInfo[] DecoratedMethods, string AssemblyPath, string[] AliasCategories) FindAssemblyToAnalyze(IPackageCoreReader package, string[] assembliesPath)
        {
            foreach (var assemblyPath in assembliesPath)
            {
                var runtimeAssemblies = Directory.GetFiles(RuntimeEnvironment.GetRuntimeDirectory(), "*.dll");

                // The assembly resolver makes the assemblies referenced by THIS APPLICATION (i.e.: the AddinDiscoverer) available
                // for resolving types when looping through custom attributes. As of this writing, there is one addin written in
                // FSharp which was causing 'Could not find FSharp.Core' when looping through its custom attributes. To solve this
                // problem, I added a reference to FSharp.Core in Cake.AddinDiscoverer.csproj
                var assemblyResolver = new PathAssemblyResolver(runtimeAssemblies);

                // It's important to create a new load context for each assembly to ensure one addin does not interfere with another
                var loadContext = new MetadataLoadContext(assemblyResolver);

                // Load the assembly
                var assemblyStream = LoadFileFromPackage(package, assemblyPath);
                var assembly       = loadContext.LoadFromStream(assemblyStream);

                var isModule = assembly
                               .CustomAttributes
                               .Any(a => a.AttributeType.Namespace == "Cake.Core.Annotations" && a.AttributeType.Name == "CakeModuleAttribute");

                // Search for decorated methods.
                // Please note that it's important to use the '.ExportedTypes' and the '.CustomAttributes' properties rather than
                // the '.GetExportedTypes' and the '.GetCustomAttributes' methods because the latter will instantiate the custom
                // attributes which, in our case, will cause exceptions because they are defined in dependencies which are most
                // likely not available in the load context.
                var decoratedMethods = assembly
                                       .ExportedTypes
                                       .SelectMany(type => type.GetTypeInfo().DeclaredMethods)
                                       .Where(method =>
                                              method.CustomAttributes.Any(a =>
                                                                          a.AttributeType.Namespace == "Cake.Core.Annotations" &&
                                                                          (a.AttributeType.Name == "CakeMethodAliasAttribute" || a.AttributeType.Name == "CakePropertyAliasAttribute")))
                                       .ToArray();

                // Search for alias categories
                var aliasCategories = assembly
                                      .ExportedTypes
                                      .SelectMany(t => t.CustomAttributes)
                                      .Where(a => a.AttributeType.Namespace == "Cake.Core.Annotations" && a.AttributeType.Name == "CakeAliasCategoryAttribute")
                                      .Select(a => a.ConstructorArguments[0].Value?.ToString())
                                      .Where(category => !string.IsNullOrEmpty(category))
                                      .Distinct(StringComparer.OrdinalIgnoreCase)
                                      .ToArray();

                if (isModule || decoratedMethods.Any())
                {
                    return(assemblyStream, assembly, decoratedMethods, assemblyPath, aliasCategories);
                }
            }

            return(null, null, Array.Empty <MethodInfo>(), string.Empty, Array.Empty <string>());
        }
 public static IEnumerable <string> GetPackageFiles(this IPackageCoreReader packageReader, PackageSaveMode packageSaveMode)
 {
     return(packageReader.GetFiles().Where(file => PackageHelper.IsPackageFile(file, packageSaveMode)));
 }
Example #8
0
        internal static void AddFiles(IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem,
                                      IPackageCoreReader packageReader,
                                      FrameworkSpecificGroup frameworkSpecificGroup,
                                      IDictionary <FileTransformExtensions, IPackageFileTransformer> fileTransformers)
        {
            var packageTargetFramework = frameworkSpecificGroup.TargetFramework;

            var packageItemListAsArchiveEntryNames = frameworkSpecificGroup.Items.ToList();

            packageItemListAsArchiveEntryNames.Sort(new PackageItemComparer());
            try
            {
                try
                {
                    var paths = packageItemListAsArchiveEntryNames.Select(file => ResolvePath(fileTransformers, fte => fte.InstallExtension,
                                                                                              GetEffectivePathForContentFile(packageTargetFramework, file)));
                    paths = paths.Where(p => !string.IsNullOrEmpty(p));

                    msBuildNuGetProjectSystem.BeginProcessing();
                    msBuildNuGetProjectSystem.RegisterProcessedFiles(paths);
                }
                catch (Exception)
                {
                    // Ignore all exceptions for now
                }

                foreach (var file in packageItemListAsArchiveEntryNames)
                {
                    if (IsEmptyFolder(file))
                    {
                        continue;
                    }

                    var effectivePathForContentFile = GetEffectivePathForContentFile(packageTargetFramework, file);

                    // Resolve the target path
                    IPackageFileTransformer installTransformer;
                    var path = ResolveTargetPath(msBuildNuGetProjectSystem,
                                                 fileTransformers,
                                                 fte => fte.InstallExtension, effectivePathForContentFile, out installTransformer);

                    if (msBuildNuGetProjectSystem.IsSupportedFile(path))
                    {
                        if (installTransformer != null)
                        {
                            installTransformer.TransformFile(() => packageReader.GetStream(file), path, msBuildNuGetProjectSystem);
                        }
                        else
                        {
                            // Ignore uninstall transform file during installation
                            string truncatedPath;
                            var    uninstallTransformer =
                                FindFileTransformer(fileTransformers, fte => fte.UninstallExtension, effectivePathForContentFile, out truncatedPath);
                            if (uninstallTransformer != null)
                            {
                                continue;
                            }
                            TryAddFile(msBuildNuGetProjectSystem, path, () => packageReader.GetStream(file));
                        }
                    }
                }
            }
            finally
            {
                msBuildNuGetProjectSystem.EndProcessing();
            }
        }
Example #9
0
 public PackageCoreReaderProxy(IPackageCoreReader reader, PackageSearchSourceProxy metadata, NuGetVersion version)
 {
     _reader   = reader;
     _metadata = metadata;
     _version  = version;
 }