示例#1
0
        // Add all reference items to the assembly list
        private void AddReferencedAssemblies(PackageIdentity packageIdentify, DirectoryPath installedPath, PackageArchiveReader archiveReader)
        {
            List <FrameworkSpecificGroup> referenceItems = archiveReader.GetReferenceItems().ToList();
            FrameworkSpecificGroup        referenceGroup = GetMostCompatibleGroup(_currentFramework, referenceItems);

            if (referenceGroup != null)
            {
                Trace.Verbose($"Found compatible reference group {referenceGroup.TargetFramework.DotNetFrameworkName} for package {packageIdentify}");
                foreach (FilePath itemPath in referenceGroup.Items
                         .Select(x => new FilePath(x))
                         .Where(x => x.FileName.Extension == ".dll" || x.FileName.Extension == ".exe"))
                {
                    FilePath assemblyPath = installedPath.CombineFile(itemPath);
                    _assemblyLoader.Add(assemblyPath.FullPath);
                    Trace.Verbose($"Added NuGet reference {assemblyPath} from package {packageIdentify} for loading");
                }
            }
            else if (referenceItems.Count == 0)
            {
                // Only show a verbose message if there were no reference items (I.e., it's probably a content-only package or a metapackage and not a mismatch)
                Trace.Verbose($"Could not find any reference items in package {packageIdentify}");
            }
            else
            {
                Trace.Verbose($"Could not find compatible reference group for package {packageIdentify} (found {string.Join(",", referenceItems.Select(x => x.TargetFramework.DotNetFrameworkName))})");
            }
        }
示例#2
0
        /// <summary>
        /// Asynchronously gets build items.
        /// </summary>
        /// <param name="cancellationToken">A cancellation token.</param>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result (<see cref="Task{TResult}.Result" />) returns an
        /// <see cref="IEnumerable{FrameworkSpecificGroup}" />.</returns>
        /// <exception cref="OperationCanceledException">Thrown if <paramref name="cancellationToken" />
        /// is cancelled.</exception>
        public override async Task <IEnumerable <FrameworkSpecificGroup> > GetBuildItemsAsync(
            CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var nuspecReader = await GetNuspecReaderAsync(cancellationToken);

            var id = nuspecReader.GetIdentity().Id;

            var results = new List <FrameworkSpecificGroup>();

            foreach (var group in await GetFileGroupsAsync(PackagingConstants.Folders.Build, cancellationToken))
            {
                var filteredGroup = group;

                if (group.Items.Any(e => !IsAllowedBuildFile(id, e)))
                {
                    // create a new group with only valid files
                    filteredGroup = new FrameworkSpecificGroup(group.TargetFramework, group.Items.Where(e => IsAllowedBuildFile(id, e)));

                    if (!filteredGroup.Items.Any())
                    {
                        // nothing was useful in the folder, skip this group completely
                        filteredGroup = null;
                    }
                }

                if (filteredGroup != null)
                {
                    results.Add(filteredGroup);
                }
            }

            return(results);
        }
示例#3
0
        /// <summary>Returns the referenced .dll/.exe file paths</summary>
        public IEnumerable <FilePath> GetReferencedAssembliesFilePaths(FolderNuGetProject project,
                                                                       NuGetFramework targetFramework)
        {
            var pkgPath       = GetPackageDirectoryPath(project);
            var archiveReader = GetArchiveReader(project);

            List <FrameworkSpecificGroup> referenceItems = archiveReader.GetReferenceItems().ToList();
            FrameworkSpecificGroup        referenceGroup = SelectFrameworkMostCompatibleGroup(targetFramework, referenceItems);

            if (referenceGroup != null)
            {
                LogTo.Verbose(
                    $"Found compatible reference group {referenceGroup.TargetFramework.DotNetFrameworkName} for package {Identity}");

                foreach (FilePath assemblyPath in referenceGroup.Items
                         .Select(x => new FilePath(x))
                         .Where(x => x.Extension == ".dll" || x.Extension == ".exe")
                         .Select(pkgPath.CombineFile))
                {
                    LogTo.Verbose($"Found NuGet reference {assemblyPath} from package {Identity}");

                    yield return(assemblyPath);
                }
            }
            else if (referenceItems.Count == 0)
            {
                // Only show a verbose message if there were no reference items (I.e., it's probably a content-only package or a metapackage and not a mismatch)
                LogTo.Verbose($"Could not find any reference items in package {Identity}");
            }
            else
            {
                LogTo.Verbose(
                    $"Could not find compatible reference group for package {Identity} (found {string.Join(",", referenceItems.Select(x => x.TargetFramework.DotNetFrameworkName))})");
            }
        }
示例#4
0
        private static JToken WritePackageReferenceSet(FrameworkSpecificGroup item)
        {
            var json = new JObject();

            json["targetFramework"] = item.TargetFramework?.ToString();
            json["references"]      = WriteArray(item.Items, WriteString);
            return(json);
        }
        void AddPackageLibFile(string framework, string fileName)
        {
            var files = new List <string> ();

            files.Add(fileName);
            var nugetFramework = NuGetFramework.Parse(framework);
            var item           = new FrameworkSpecificGroup(nugetFramework, files);

            packageFilesReader.LibItems.Add(item);
        }
示例#6
0
        private static bool IsValid(FrameworkSpecificGroup frameworkSpecificGroup)
        {
            if (frameworkSpecificGroup != null)
            {
                return(frameworkSpecificGroup.HasEmptyFolder ||
                       frameworkSpecificGroup.Items.Any() ||
                       !frameworkSpecificGroup.TargetFramework.Equals(NuGetFramework.AnyFramework));
            }

            return(false);
        }
        private static IList<LibraryDependency> GetDependencies(NuGetFramework targetFramework,
            PackageDependencyGroup dependencies,
            FrameworkSpecificGroup frameworkAssemblies)
        {
            var libraryDependencies = new List<LibraryDependency>();

            if (dependencies != null)
            {
                foreach (var d in dependencies.Packages)
                {
                    libraryDependencies.Add(new LibraryDependency
                        {
                            LibraryRange = new LibraryRange
                                {
                                    Name = d.Id,
                                    VersionRange = d.VersionRange
                                }
                        });
                }
            }

            if (frameworkAssemblies == null)
            {
                return libraryDependencies;
            }

            if (!targetFramework.IsDesktop())
            {
                // REVIEW: This isn't 100% correct since none *can* mean 
                // any in theory, but in practice it means .NET full reference assembly
                // If there's no supported target frameworks and we're not targeting
                // the desktop framework then skip it.

                // To do this properly we'll need all reference assemblies supported
                // by each supported target framework which isn't always available.
                return libraryDependencies;
            }

            foreach (var name in frameworkAssemblies.Items)
            {
                libraryDependencies.Add(new LibraryDependency
                    {
                        LibraryRange = new LibraryRange
                            {
                                Name = name,
                                TypeConstraint = LibraryTypes.Reference
                            }
                    });
            }

            return libraryDependencies;
        }
示例#8
0
        private static IList <LibraryDependency> GetDependencies(NuGetFramework targetFramework,
                                                                 PackageDependencyGroup dependencies,
                                                                 FrameworkSpecificGroup frameworkAssemblies)
        {
            var libraryDependencies = new List <LibraryDependency>();

            if (dependencies != null)
            {
                foreach (var d in dependencies.Packages)
                {
                    libraryDependencies.Add(new LibraryDependency
                    {
                        LibraryRange = new LibraryRange
                        {
                            Name         = d.Id,
                            VersionRange = d.VersionRange
                        }
                    });
                }
            }

            if (frameworkAssemblies == null)
            {
                return(libraryDependencies);
            }

            if (!targetFramework.IsDesktop())
            {
                // REVIEW: This isn't 100% correct since none *can* mean
                // any in theory, but in practice it means .NET full reference assembly
                // If there's no supported target frameworks and we're not targeting
                // the desktop framework then skip it.

                // To do this properly we'll need all reference assemblies supported
                // by each supported target framework which isn't always available.
                return(libraryDependencies);
            }

            foreach (var name in frameworkAssemblies.Items)
            {
                libraryDependencies.Add(new LibraryDependency
                {
                    LibraryRange = new LibraryRange
                    {
                        Name           = name,
                        TypeConstraint = LibraryTypes.Reference
                    }
                });
            }

            return(libraryDependencies);
        }
        private FrameworkSpecificGroup?GetMostCompatibleGroup(NuGetFramework projectTargetFramework,
                                                              IEnumerable <FrameworkSpecificGroup> itemGroups)
        {
            NuGetFramework mostCompatibleFramework = new FrameworkReducer()
                                                     .GetNearest(projectTargetFramework, itemGroups.Select(i => i.TargetFramework));

            if (mostCompatibleFramework is null)
            {
                return(null);
            }

            FrameworkSpecificGroup mostCompatibleGroup = itemGroups.FirstOrDefault(i => i.TargetFramework.Equals(mostCompatibleFramework));

            return(IsValid(mostCompatibleGroup) ? mostCompatibleGroup : null);
        }
示例#10
0
        // Add content directories to the input paths
        private IEnumerable <DirectoryPath> GetContentDirectories(DirectoryPath installedPath, PackageArchiveReader archiveReader)
        {
            FrameworkSpecificGroup contentGroup = GetMostCompatibleGroup(_currentFramework, archiveReader.GetContentItems().ToList());

            if (contentGroup != null)
            {
                // We need to use the directory name from an actual file to make sure we get the casing right
                foreach (string contentSegment in contentGroup.Items
                         .Select(x => new FilePath(x).Segments[0])
                         .Distinct())
                {
                    yield return(installedPath.Combine(contentSegment));
                }
            }
        }
示例#11
0
        // Add all reference items to the assembly list
        private void AddReferencedAssemblies(DirectoryPath installedPath, PackageArchiveReader archiveReader)
        {
            FrameworkSpecificGroup referenceGroup = GetMostCompatibleGroup(_currentFramework, archiveReader.GetReferenceItems().ToList());

            if (referenceGroup != null)
            {
                foreach (FilePath itemPath in referenceGroup.Items
                         .Select(x => new FilePath(x))
                         .Where(x => x.FileName.Extension == ".dll" || x.FileName.Extension == ".exe"))
                {
                    FilePath assemblyPath = installedPath.CombineFile(itemPath);
                    _assemblyLoader.Add(assemblyPath.FullPath);
                    Trace.Verbose($"Added NuGet reference {assemblyPath} for loading");
                }
            }
        }
示例#12
0
        // Add content directories to the input paths
        private IEnumerable <DirectoryPath> GetContentDirectories(PackageIdentity packageIdentify, DirectoryPath installedPath, PackageArchiveReader archiveReader)
        {
            FrameworkSpecificGroup contentGroup = GetMostCompatibleGroup(_currentFramework, archiveReader.GetContentItems().ToList());

            if (contentGroup != null)
            {
                // We need to use the directory name from an actual file to make sure we get the casing right
                foreach (string contentSegment in contentGroup.Items
                         .Select(x => new FilePath(x).Segments[0])
                         .Distinct())
                {
                    DirectoryPath contentPath = installedPath.Combine(contentSegment);
                    Trace.Verbose($"Added content path {contentPath} from compatible content group {contentGroup.TargetFramework.DotNetFrameworkName} from package {packageIdentify} to included paths");
                    yield return(contentPath);
                }
            }
        }
示例#13
0
        // Add content directories to the input paths
        private void IncludeContentDirectories(DirectoryPath installedPath, PackageArchiveReader archiveReader)
        {
            FrameworkSpecificGroup contentGroup = GetMostCompatibleGroup(_reducer,
                                                                         _currentFramework, archiveReader.GetContentItems().ToList());

            if (contentGroup != null)
            {
                // We need to use the directory name from an actual file to make sure we get the casing right
                foreach (string contentSegment in contentGroup.Items
                         .Select(x => new FilePath(x).Segments[0])
                         .Distinct())
                {
                    DirectoryPath contentPath = installedPath.Combine(contentSegment);
                    _fileSystem.InputPaths.Insert(0, contentPath);
                    Trace.Verbose($"Added content path {contentPath} to included paths");
                }
            }
        }
示例#14
0
        private async Task <List <string> > GetSatelliteFilesForLibraryAsync(FrameworkSpecificGroup libraryFrameworkSpecificGroup, PackageReaderBase packageReader,
                                                                             CancellationToken cancellationToken)
        {
            var satelliteFiles = new List <string>();

            using (var nuspec = await packageReader.GetNuspecAsync(cancellationToken))
            {
                var nuspecReader = new NuspecReader(nuspec);

                var satelliteFilesInGroup = libraryFrameworkSpecificGroup.Items
                                            .Where(item => Path.GetDirectoryName(item)
                                                   .Split(Path.DirectorySeparatorChar)
                                                   .Contains(nuspecReader.GetLanguage(), StringComparer.OrdinalIgnoreCase)).ToList();

                satelliteFiles.AddRange(satelliteFilesInGroup);

                return(satelliteFiles);
            }
        }
示例#15
0
        private static FrameworkSpecificGroup Normalize(FrameworkSpecificGroup group)
        {
            // Default to returning the same group
            FrameworkSpecificGroup result = group;

            // If the group is null or it does not contain any items besides _._ then this is a no-op.
            // If it does have items create a new normalized group to replace it with.
            if (group?.Items.Any() == true)
            {
                // Filter out invalid files
                IEnumerable <string> normalizedItems = GetValidPackageItems(group.Items)
                                                       .Select(PathUtility.ReplaceAltDirSeparatorWithDirSeparator);

                // Create a new group
                result = new FrameworkSpecificGroup(group.TargetFramework, normalizedItems);
            }

            return(result);
        }
        internal static FrameworkSpecificGroup GetMostCompatibleGroup(NuGetFramework projectTargetFramework, IEnumerable<FrameworkSpecificGroup> itemGroups,
            bool altDirSeparator = false)
        {
            FrameworkReducer reducer = new FrameworkReducer();
            NuGetFramework mostCompatibleFramework = reducer.GetNearest(projectTargetFramework, itemGroups.Select(i => i.TargetFramework));
            if (mostCompatibleFramework != null)
            {
                IEnumerable<FrameworkSpecificGroup> mostCompatibleGroups = itemGroups.Where(i => i.TargetFramework.Equals(mostCompatibleFramework));
                var mostCompatibleGroup = mostCompatibleGroups.SingleOrDefault();
                if (IsValid(mostCompatibleGroup))
                {
                    mostCompatibleGroup = new FrameworkSpecificGroup(mostCompatibleGroup.TargetFramework,
                        GetValidPackageItems(mostCompatibleGroup.Items).Select(item => altDirSeparator ? PathUtility.ReplaceDirSeparatorWithAltDirSeparator(item)
                            : PathUtility.ReplaceAltDirSeparatorWithDirSeparator(item)));
                }

                return mostCompatibleGroup;
            }
            return null;
        }
示例#17
0
        /// The following method is originally from the internal MSBuildNuGetProjectSystemUtility class
        private static FrameworkSpecificGroup SelectFrameworkMostCompatibleGroup(NuGetFramework projectTargetFramework,
                                                                                 List <FrameworkSpecificGroup> itemGroups)
        {
            FrameworkReducer reducer = new FrameworkReducer();
            NuGetFramework   mostCompatibleFramework
                = reducer.GetNearest(projectTargetFramework, itemGroups.Select(i => i.TargetFramework));

            if (mostCompatibleFramework != null)
            {
                FrameworkSpecificGroup mostCompatibleGroup
                    = itemGroups.FirstOrDefault(i => i.TargetFramework.Equals(mostCompatibleFramework));

                if (IsValidFrameworkGroup(mostCompatibleGroup))
                {
                    return(mostCompatibleGroup);
                }
            }

            return(null);
        }
示例#18
0
        // Probably going to hell for using a region
        // The following methods are originally from the internal MSBuildNuGetProjectSystemUtility class
        #region MSBuildNuGetProjectSystemUtility

        private static FrameworkSpecificGroup GetMostCompatibleGroup(FrameworkReducer reducer, NuGetFramework projectTargetFramework,
                                                                     ICollection <FrameworkSpecificGroup> itemGroups)
        {
            NuGetFramework mostCompatibleFramework
                = reducer.GetNearest(projectTargetFramework, itemGroups.Select(i => i.TargetFramework));

            if (mostCompatibleFramework != null)
            {
                FrameworkSpecificGroup mostCompatibleGroup = itemGroups
                                                             .FirstOrDefault(i => i.TargetFramework.Equals(mostCompatibleFramework));

                if (IsValid(mostCompatibleGroup))
                {
                    // Normalize() is called outside GetMostCompatibleGroup() in MSBuildNuGetProjectSystemUtility but I combined it
                    return(Normalize(mostCompatibleGroup));
                }
            }

            return(null);
        }
示例#19
0
        internal static FrameworkSpecificGroup GetMostCompatibleGroup(NuGetFramework projectTargetFramework, IEnumerable <FrameworkSpecificGroup> itemGroups,
                                                                      bool altDirSeparator = false)
        {
            FrameworkReducer reducer = new FrameworkReducer();
            NuGetFramework   mostCompatibleFramework = reducer.GetNearest(projectTargetFramework, itemGroups.Select(i => i.TargetFramework));

            if (mostCompatibleFramework != null)
            {
                IEnumerable <FrameworkSpecificGroup> mostCompatibleGroups = itemGroups.Where(i => i.TargetFramework.Equals(mostCompatibleFramework));
                var mostCompatibleGroup = mostCompatibleGroups.SingleOrDefault();
                if (IsValid(mostCompatibleGroup))
                {
                    mostCompatibleGroup = new FrameworkSpecificGroup(mostCompatibleGroup.TargetFramework,
                                                                     GetValidPackageItems(mostCompatibleGroup.Items).Select(item => altDirSeparator ? PathUtility.ReplaceDirSeparatorWithAltDirSeparator(item)
                            : PathUtility.ReplaceAltDirSeparatorWithDirSeparator(item)));
                }

                return(mostCompatibleGroup);
            }
            return(null);
        }
示例#20
0
        public static IEnumerable <DirectoryPath> GetContentDirectoryPath(
            this NuGetPackage pkg,
            FolderNuGetProject project,
            NuGetFramework targetFramework)
        {
            if (pkg == null)
            {
                yield break;
            }

            var pkgPath = pkg.GetPackageDirectoryPath(project);

            if (pkgPath == null)
            {
                yield break;
            }

            var archiveReader = pkg.GetArchiveReader(project);

            if (archiveReader == null)
            {
                yield break;
            }

            FrameworkSpecificGroup contentGroup = SelectFrameworkMostCompatibleGroup(targetFramework, archiveReader.GetContentItems().ToList());

            if (contentGroup != null)
            {
                foreach (DirectoryPath contentPath in contentGroup.Items.Select(x => new FilePath(x).Segments[0])
                         .Distinct()
                         .Select(x => pkgPath.Combine(x)))
                {
                    LogTo.Trace(
                        $"Found content path {contentPath} from compatible content group {contentGroup.TargetFramework.DotNetFrameworkName} from package {pkg.Identity}");

                    yield return(contentPath);
                }
            }
        }
        internal static void DeleteFiles(IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem,
                                            ZipArchive zipArchive,
                                            IEnumerable<string> otherPackagesPath,
                                            FrameworkSpecificGroup frameworkSpecificGroup,
                                            IDictionary<FileTransformExtensions, IPackageFileTransformer> fileTransformers)
        {
            var packageTargetFramework = frameworkSpecificGroup.TargetFramework;
            IPackageFileTransformer transformer;
            var directoryLookup = frameworkSpecificGroup.Items.ToLookup(
                p => Path.GetDirectoryName(ResolveTargetPath(msBuildNuGetProjectSystem,
                    fileTransformers,
                    fte => fte.UninstallExtension,
                    GetEffectivePathForContentFile(packageTargetFramework, p),
                    out transformer)));

            // Get all directories that this package may have added
            var directories = from grouping in directoryLookup
                              from directory in FileSystemUtility.GetDirectories(grouping.Key, altDirectorySeparator: false)
                              orderby directory.Length descending
                              select directory;

            // Remove files from every directory
            foreach (var directory in directories)
            {
                var directoryFiles = directoryLookup.Contains(directory) ? directoryLookup[directory] : Enumerable.Empty<string>();

                if (!Directory.Exists(Path.Combine(msBuildNuGetProjectSystem.ProjectFullPath, directory)))
                {
                    continue;
                }

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

                        // Resolve the path
                        string path = ResolveTargetPath(msBuildNuGetProjectSystem,
                                                        fileTransformers,
                                                        fte => fte.UninstallExtension,
                                                        GetEffectivePathForContentFile(packageTargetFramework, file),
                                                        out transformer);

                        if (msBuildNuGetProjectSystem.IsSupportedFile(path))
                        {
                            if (transformer != null)
                            {
                                // TODO: use the framework from packages.config instead of the current framework
                                // which may have changed during re-targeting
                                NuGetFramework projectFramework = msBuildNuGetProjectSystem.TargetFramework;

                                List<InternalZipFileInfo> matchingFiles = new List<InternalZipFileInfo>();
                                foreach(var otherPackagePath in otherPackagesPath)
                                {
                                    using(var otherPackageStream = File.OpenRead(otherPackagePath))
                                    {
                                        var otherPackageZipArchive = new ZipArchive(otherPackageStream);
                                        var otherPackageZipReader = new PackageReader(otherPackageZipArchive);

                                        // use the project framework to find the group that would have been installed
                                        var mostCompatibleContentFilesGroup = GetMostCompatibleGroup(projectFramework, otherPackageZipReader.GetContentItems(), altDirSeparator: true);
                                        if(mostCompatibleContentFilesGroup != null && IsValid(mostCompatibleContentFilesGroup))
                                        {
                                            foreach(var otherPackageItem in mostCompatibleContentFilesGroup.Items)
                                            {
                                                if(GetEffectivePathForContentFile(packageTargetFramework, otherPackageItem)
                                                    .Equals(GetEffectivePathForContentFile(packageTargetFramework, file), StringComparison.OrdinalIgnoreCase))
                                                {
                                                    matchingFiles.Add(new InternalZipFileInfo(otherPackagePath, otherPackageItem));
                                                }
                                            }
                                        }
                                    }
                                }

                                try
                                {
                                    var zipArchiveFileEntry = zipArchive.GetEntry(PathUtility.ReplaceDirSeparatorWithAltDirSeparator(file));
                                    if (zipArchiveFileEntry != null)
                                    {
                                        transformer.RevertFile(zipArchiveFileEntry, path, matchingFiles, msBuildNuGetProjectSystem);
                                    }
                                }
                                catch (Exception e)
                                {
                                    msBuildNuGetProjectSystem.NuGetProjectContext.Log(MessageLevel.Warning, e.Message);
                                }
                            }
                            else
                            {
                                var zipArchiveFileEntry = zipArchive.GetEntry(PathUtility.ReplaceDirSeparatorWithAltDirSeparator(file));
                                if (zipArchiveFileEntry != null)
                                {
                                    DeleteFileSafe(path, zipArchiveFileEntry.Open, msBuildNuGetProjectSystem);
                                }
                            }
                        }
                    }


                    // If the directory is empty then delete it
                    if (!GetFilesSafe(msBuildNuGetProjectSystem, directory).Any() &&
                        !GetDirectoriesSafe(msBuildNuGetProjectSystem, directory).Any())
                    {
                        DeleteDirectorySafe(msBuildNuGetProjectSystem, directory, recursive: false);
                    }
                }
                finally
                {

                }
            }
        }
示例#22
0
        public IEnumerable<FrameworkSpecificGroup> GetBuildItems()
        {
            var id = GetIdentity().Id;

            var results = new List<FrameworkSpecificGroup>();

            foreach (var group in GetFileGroups("build"))
            {
                var filteredGroup = group;

                if (group.Items.Any(e => !IsAllowedBuildFile(id, e)))
                {
                    // create a new group with only valid files
                    filteredGroup = new FrameworkSpecificGroup(group.TargetFramework, group.Items.Where(e => IsAllowedBuildFile(id, e)));

                    if (!filteredGroup.Items.Any())
                    {
                        // nothing was useful in the folder, skip this group completely
                        filteredGroup = null;
                    }
                }

                if (filteredGroup != null)
                {
                    results.Add(filteredGroup);
                }
            }

            return results;
        }
示例#23
0
        internal static void AddFiles(IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem,
                                      ZipArchive zipArchive,
                                      FrameworkSpecificGroup frameworkSpecificGroup,
                                      IDictionary <FileTransformExtensions, IPackageFileTransformer> fileTransformers)
        {
            var packageTargetFramework = frameworkSpecificGroup.TargetFramework;

            // Content files are maintained with AltDirectorySeparatorChar
            List <string> packageItemListAsArchiveEntryNames = frameworkSpecificGroup.Items.Select(i => PathUtility.ReplaceDirSeparatorWithAltDirSeparator(i)).ToList();

            packageItemListAsArchiveEntryNames.Sort(new PackageItemComparer());
            try
            {
                var zipArchiveEntryList = packageItemListAsArchiveEntryNames.Select(i => zipArchive.GetEntry(i)).Where(i => i != null).ToList();
                try
                {
                    var paths = zipArchiveEntryList.Select(file => ResolvePath(fileTransformers, fte => fte.InstallExtension,
                                                                               GetEffectivePathForContentFile(packageTargetFramework, file.FullName)));
                    paths = paths.Where(p => !String.IsNullOrEmpty(p));
                    msBuildNuGetProjectSystem.BeginProcessing(paths);
                }
                catch (Exception)
                {
                    // Ignore all exceptions for now
                }

                foreach (ZipArchiveEntry zipArchiveEntry in zipArchiveEntryList)
                {
                    if (zipArchiveEntry == null)
                    {
                        throw new ArgumentNullException("zipArchiveEntry");
                    }

                    if (IsEmptyFolder(zipArchiveEntry.FullName))
                    {
                        continue;
                    }

                    var effectivePathForContentFile = GetEffectivePathForContentFile(packageTargetFramework, zipArchiveEntry.FullName);

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

                    if (msBuildNuGetProjectSystem.IsSupportedFile(path))
                    {
                        if (installTransformer != null)
                        {
                            installTransformer.TransformFile(zipArchiveEntry, path, msBuildNuGetProjectSystem);
                        }
                        else
                        {
                            // Ignore uninstall transform file during installation
                            string truncatedPath;
                            IPackageFileTransformer uninstallTransformer =
                                FindFileTransformer(fileTransformers, fte => fte.UninstallExtension, effectivePathForContentFile, out truncatedPath);
                            if (uninstallTransformer != null)
                            {
                                continue;
                            }
                            TryAddFile(msBuildNuGetProjectSystem, path, zipArchiveEntry.Open);
                        }
                    }
                }
            }
            finally
            {
                msBuildNuGetProjectSystem.EndProcessing();
            }
        }
示例#24
0
        /// <summary>
        /// Framework reference groups
        /// </summary>
        public IEnumerable<FrameworkSpecificGroup> GetFrameworkReferenceGroups()
        {
            var results = new List<FrameworkSpecificGroup>();

            var ns = Xml.Root.GetDefaultNamespace().NamespaceName;

            var groups = new Dictionary<NuGetFramework, HashSet<string>>(new NuGetFrameworkFullComparer());

            foreach (var group in MetadataNode.Elements(XName.Get(FrameworkAssemblies, ns)).Elements(XName.Get(FrameworkAssembly, ns))
                .GroupBy(n => GetAttributeValue(n, TargetFramework)))
            {
                // Framework references may have multiple comma delimited frameworks
                var frameworks = new List<NuGetFramework>();

                // Empty frameworks go under Any
                if (String.IsNullOrEmpty(group.Key))
                {
                    frameworks.Add(NuGetFramework.AnyFramework);
                }
                else
                {
                    foreach (var fwString in group.Key.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        if (!String.IsNullOrEmpty(fwString))
                        {
                            frameworks.Add(NuGetFramework.Parse(fwString.Trim(), _frameworkProvider));
                        }
                    }
                }

                // apply items to each framework
                foreach (var framework in frameworks)
                {
                    HashSet<string> items = null;
                    if (!groups.TryGetValue(framework, out items))
                    {
                        items = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
                        groups.Add(framework, items);
                    }

                    // Merge items and ignore duplicates
                    items.UnionWith(group.Select(item => GetAttributeValue(item, AssemblyName)).Where(item => !String.IsNullOrEmpty(item)));
                }
            }

            // Sort items to make this deterministic for the caller
            foreach (var framework in groups.Keys.OrderBy(e => e, new NuGetFrameworkSorter()))
            {
                var group = new FrameworkSpecificGroup(framework, groups[framework].OrderBy(item => item, StringComparer.OrdinalIgnoreCase));

                results.Add(group);
            }

            return results;
        }
        public async override Task <bool> InstallPackageAsync(PackageIdentity packageIdentity, Stream packageStream,
                                                              INuGetProjectContext nuGetProjectContext, CancellationToken token)
        {
            if (packageIdentity == null)
            {
                throw new ArgumentNullException("packageIdentity");
            }

            if (packageStream == null)
            {
                throw new ArgumentNullException("packageStream");
            }

            if (nuGetProjectContext == null)
            {
                throw new ArgumentNullException("nuGetProjectContext");
            }

            if (!packageStream.CanSeek)
            {
                throw new ArgumentException(Strings.PackageStreamShouldBeSeekable);
            }

            // Step-1: Check if the package already exists after setting the nuGetProjectContext
            MSBuildNuGetProjectSystem.SetNuGetProjectContext(nuGetProjectContext);

            var packageReference = (await GetInstalledPackagesAsync(token)).Where(
                p => p.PackageIdentity.Equals(packageIdentity)).FirstOrDefault();

            if (packageReference != null)
            {
                nuGetProjectContext.Log(MessageLevel.Warning, Strings.PackageAlreadyExistsInProject,
                                        packageIdentity, MSBuildNuGetProjectSystem.ProjectName);
                return(false);
            }

            // Step-2: Create PackageReader using the PackageStream and obtain the various item groups
            packageStream.Seek(0, SeekOrigin.Begin);
            var           zipArchive    = new ZipArchive(packageStream);
            PackageReader packageReader = new PackageReader(zipArchive);
            IEnumerable <FrameworkSpecificGroup> referenceItemGroups      = packageReader.GetReferenceItems();
            IEnumerable <FrameworkSpecificGroup> frameworkReferenceGroups = packageReader.GetFrameworkItems();
            IEnumerable <FrameworkSpecificGroup> contentFileGroups        = packageReader.GetContentItems();
            IEnumerable <FrameworkSpecificGroup> buildFileGroups          = packageReader.GetBuildItems();
            IEnumerable <FrameworkSpecificGroup> toolItemGroups           = packageReader.GetToolItems();

            // Step-3: Get the most compatible items groups for all items groups
            bool hasCompatibleProjectLevelContent = false;

            FrameworkSpecificGroup compatibleReferenceItemsGroup =
                MSBuildNuGetProjectSystemUtility.GetMostCompatibleGroup(MSBuildNuGetProjectSystem.TargetFramework, referenceItemGroups);
            FrameworkSpecificGroup compatibleFrameworkReferencesGroup =
                MSBuildNuGetProjectSystemUtility.GetMostCompatibleGroup(MSBuildNuGetProjectSystem.TargetFramework, frameworkReferenceGroups);
            FrameworkSpecificGroup compatibleContentFilesGroup =
                MSBuildNuGetProjectSystemUtility.GetMostCompatibleGroup(MSBuildNuGetProjectSystem.TargetFramework, contentFileGroups);
            FrameworkSpecificGroup compatibleBuildFilesGroup =
                MSBuildNuGetProjectSystemUtility.GetMostCompatibleGroup(MSBuildNuGetProjectSystem.TargetFramework, buildFileGroups);
            FrameworkSpecificGroup compatibleToolItemsGroup =
                MSBuildNuGetProjectSystemUtility.GetMostCompatibleGroup(MSBuildNuGetProjectSystem.TargetFramework, toolItemGroups);

            hasCompatibleProjectLevelContent = MSBuildNuGetProjectSystemUtility.IsValid(compatibleReferenceItemsGroup) ||
                                               MSBuildNuGetProjectSystemUtility.IsValid(compatibleFrameworkReferencesGroup) ||
                                               MSBuildNuGetProjectSystemUtility.IsValid(compatibleContentFilesGroup) ||
                                               MSBuildNuGetProjectSystemUtility.IsValid(compatibleBuildFilesGroup);

            // Check if package has any content for project
            bool hasProjectLevelContent = referenceItemGroups.Any() || frameworkReferenceGroups.Any() ||
                                          contentFileGroups.Any() || buildFileGroups.Any();
            bool onlyHasCompatibleTools = false;
            bool onlyHasDependencies    = false;

            if (!hasProjectLevelContent)
            {
                // Since it does not have project-level content, check if it has dependencies or compatible tools
                // Note that we are not checking if it has compatible project level content, but, just that it has project level content
                // If the package has project-level content, but nothing compatible, we still need to throw
                // If a package does not have any project-level content, it can be a
                // Legacy solution level packages which only has compatible tools group
                onlyHasCompatibleTools = MSBuildNuGetProjectSystemUtility.IsValid(compatibleToolItemsGroup) && compatibleToolItemsGroup.Items.Any();
                if (!onlyHasCompatibleTools)
                {
                    // If it does not have compatible tool items either, check if it at least has dependencies
                    onlyHasDependencies = packageReader.GetPackageDependencies().Any();
                }
            }
            else
            {
                string shortFramework = MSBuildNuGetProjectSystem.TargetFramework.GetShortFolderName();
                nuGetProjectContext.Log(MessageLevel.Debug, Strings.Debug_TargetFrameworkInfoPrefix, packageIdentity,
                                        this.GetMetadata <string>(NuGetProjectMetadataKeys.Name), shortFramework);
            }

            // Step-4: Check if there are any compatible items in the package or that this is not a package with only tools group. If not, throw
            if (!hasCompatibleProjectLevelContent && !onlyHasCompatibleTools && !onlyHasDependencies)
            {
                throw new InvalidOperationException(
                          String.Format(CultureInfo.CurrentCulture,
                                        Strings.UnableToFindCompatibleItems, packageIdentity, MSBuildNuGetProjectSystem.TargetFramework));
            }

            if (hasCompatibleProjectLevelContent)
            {
                string shortFramework = MSBuildNuGetProjectSystem.TargetFramework.GetShortFolderName();
                nuGetProjectContext.Log(MessageLevel.Debug, Strings.Debug_TargetFrameworkInfoPrefix, packageIdentity,
                                        this.GetMetadata <string>(NuGetProjectMetadataKeys.Name), shortFramework);
            }
            else if (onlyHasCompatibleTools)
            {
                nuGetProjectContext.Log(MessageLevel.Info, Strings.AddingPackageWithOnlyToolsGroup, packageIdentity,
                                        this.GetMetadata <string>(NuGetProjectMetadataKeys.Name));
            }
            else if (onlyHasDependencies)
            {
                nuGetProjectContext.Log(MessageLevel.Info, Strings.AddingPackageWithOnlyDependencies, packageIdentity,
                                        this.GetMetadata <string>(NuGetProjectMetadataKeys.Name));
            }

            // Step-5: Raise PackageInstalling event
            // At this point, GetInstalledPath is pointless since the package is, likely, not already installed. It will be empty
            // Using PackagePathResolver.GetInstallPath would be wrong, since, package version from the nuspec is always used
            var packageEventArgs = new PackageEventArgs(FolderNuGetProject, packageIdentity, FolderNuGetProject.GetInstalledPath(packageIdentity));

            if (PackageInstalling != null)
            {
                PackageInstalling(this, packageEventArgs);
            }
            PackageEventsProvider.Instance.NotifyInstalling(packageEventArgs);

            // Step-6: Install package to FolderNuGetProject
            await FolderNuGetProject.InstallPackageAsync(packageIdentity, packageStream, nuGetProjectContext, token);

            // Step-7: Raise PackageInstalled event
            // Call GetInstalledPath again, to get the package installed path
            packageEventArgs = new PackageEventArgs(FolderNuGetProject, packageIdentity, FolderNuGetProject.GetInstalledPath(packageIdentity));
            if (PackageInstalled != null)
            {
                PackageInstalled(this, packageEventArgs);
            }
            PackageEventsProvider.Instance.NotifyInstalled(packageEventArgs);

            // Step-8: MSBuildNuGetProjectSystem operations
            // Step-8.1: Add references to project
            if (MSBuildNuGetProjectSystemUtility.IsValid(compatibleReferenceItemsGroup) && !IsSkipAssemblyReferences(nuGetProjectContext))
            {
                foreach (var referenceItem in compatibleReferenceItemsGroup.Items)
                {
                    if (IsAssemblyReference(referenceItem))
                    {
                        var referenceItemFullPath = Path.Combine(FolderNuGetProject.GetInstalledPath(packageIdentity), referenceItem);
                        var referenceName         = Path.GetFileName(referenceItem);
                        if (MSBuildNuGetProjectSystem.ReferenceExists(referenceName))
                        {
                            MSBuildNuGetProjectSystem.RemoveReference(referenceName);
                        }
                        MSBuildNuGetProjectSystem.AddReference(referenceItemFullPath);
                    }
                }
            }

            // Step-8.2: Add Frameworkreferences to project
            if (MSBuildNuGetProjectSystemUtility.IsValid(compatibleFrameworkReferencesGroup))
            {
                foreach (var frameworkReference in compatibleFrameworkReferencesGroup.Items)
                {
                    var frameworkReferenceName = Path.GetFileName(frameworkReference);
                    if (!MSBuildNuGetProjectSystem.ReferenceExists(frameworkReference))
                    {
                        MSBuildNuGetProjectSystem.AddFrameworkReference(frameworkReference);
                    }
                }
            }

            // Step-8.3: Add Content Files
            if (MSBuildNuGetProjectSystemUtility.IsValid(compatibleContentFilesGroup))
            {
                MSBuildNuGetProjectSystemUtility.AddFiles(MSBuildNuGetProjectSystem,
                                                          zipArchive, compatibleContentFilesGroup, FileTransformers);
            }

            // Step-8.4: Add Build imports
            if (MSBuildNuGetProjectSystemUtility.IsValid(compatibleBuildFilesGroup))
            {
                foreach (var buildImportFile in compatibleBuildFilesGroup.Items)
                {
                    string fullImportFilePath = Path.Combine(FolderNuGetProject.GetInstalledPath(packageIdentity), buildImportFile);
                    MSBuildNuGetProjectSystem.AddImport(fullImportFilePath,
                                                        fullImportFilePath.EndsWith(".props", StringComparison.OrdinalIgnoreCase) ? ImportLocation.Top : ImportLocation.Bottom);
                }
            }

            // Step-9: Install package to PackagesConfigNuGetProject
            await PackagesConfigNuGetProject.InstallPackageAsync(packageIdentity, packageStream, nuGetProjectContext, token);

            // Step-10: Add packages.config to MSBuildNuGetProject
            MSBuildNuGetProjectSystem.AddExistingFile(Path.GetFileName(PackagesConfigNuGetProject.FullPath));

            // Step 11: Raise PackageReferenceAdded event
            if (PackageReferenceAdded != null)
            {
                PackageReferenceAdded(this, packageEventArgs);
            }
            PackageEventsProvider.Instance.NotifyReferenceAdded(packageEventArgs);

            // Step-12: Execute powershell script - install.ps1
            string packageInstallPath = FolderNuGetProject.GetInstalledPath(packageIdentity);
            FrameworkSpecificGroup anyFrameworkToolsGroup = toolItemGroups.Where(g => g.TargetFramework.Equals(NuGetFramework.AnyFramework)).FirstOrDefault();

            if (anyFrameworkToolsGroup != null)
            {
                string initPS1RelativePath = anyFrameworkToolsGroup.Items.Where(p =>
                                                                                p.StartsWith(PowerShellScripts.InitPS1RelativePath)).FirstOrDefault();
                if (!String.IsNullOrEmpty(initPS1RelativePath))
                {
                    initPS1RelativePath = PathUtility.ReplaceAltDirSeparatorWithDirSeparator(initPS1RelativePath);
                    await MSBuildNuGetProjectSystem.ExecuteScriptAsync(packageInstallPath, initPS1RelativePath, zipArchive, this);
                }
            }

            if (MSBuildNuGetProjectSystemUtility.IsValid(compatibleToolItemsGroup))
            {
                string installPS1RelativePath = compatibleToolItemsGroup.Items.Where(p =>
                                                                                     p.EndsWith(Path.DirectorySeparatorChar + PowerShellScripts.Install)).FirstOrDefault();
                if (!String.IsNullOrEmpty(installPS1RelativePath))
                {
                    await MSBuildNuGetProjectSystem.ExecuteScriptAsync(packageInstallPath, installPS1RelativePath, zipArchive, this);
                }
            }
            return(true);
        }
        public async override Task <bool> UninstallPackageAsync(PackageIdentity packageIdentity, INuGetProjectContext nuGetProjectContext, CancellationToken token)
        {
            if (packageIdentity == null)
            {
                throw new ArgumentNullException("packageIdentity");
            }

            if (nuGetProjectContext == null)
            {
                throw new ArgumentNullException("nuGetProjectContext");
            }

            // Step-1: Check if the package already exists after setting the nuGetProjectContext
            MSBuildNuGetProjectSystem.SetNuGetProjectContext(nuGetProjectContext);

            var packageReference = (await GetInstalledPackagesAsync(token)).Where(
                p => p.PackageIdentity.Equals(packageIdentity)).FirstOrDefault();

            if (packageReference == null)
            {
                nuGetProjectContext.Log(MessageLevel.Warning, Strings.PackageDoesNotExistInProject,
                                        packageIdentity, MSBuildNuGetProjectSystem.ProjectName);
                return(false);
            }

            var packageTargetFramework = packageReference.TargetFramework ?? NuGetFramework.UnsupportedFramework;
            var packageEventArgs       = new PackageEventArgs(FolderNuGetProject, packageIdentity, FolderNuGetProject.GetInstalledPath(packageIdentity));

            using (var packageStream = File.OpenRead(FolderNuGetProject.GetInstalledPackageFilePath(packageIdentity)))
            {
                // Step-2: Create PackageReader using the PackageStream and obtain the various item groups
                // Get the package target framework instead of using project targetframework
                var zipArchive    = new ZipArchive(packageStream);
                var packageReader = new PackageReader(zipArchive);

                IEnumerable <FrameworkSpecificGroup> referenceItemGroups      = packageReader.GetReferenceItems();
                IEnumerable <FrameworkSpecificGroup> frameworkReferenceGroups = packageReader.GetFrameworkItems();
                IEnumerable <FrameworkSpecificGroup> contentFileGroups        = packageReader.GetContentItems();
                IEnumerable <FrameworkSpecificGroup> buildFileGroups          = packageReader.GetBuildItems();

                // Step-3: Get the most compatible items groups for all items groups
                FrameworkSpecificGroup compatibleReferenceItemsGroup =
                    MSBuildNuGetProjectSystemUtility.GetMostCompatibleGroup(packageTargetFramework, referenceItemGroups);
                FrameworkSpecificGroup compatibleFrameworkReferencesGroup =
                    MSBuildNuGetProjectSystemUtility.GetMostCompatibleGroup(packageTargetFramework, frameworkReferenceGroups);
                FrameworkSpecificGroup compatibleContentFilesGroup =
                    MSBuildNuGetProjectSystemUtility.GetMostCompatibleGroup(packageTargetFramework, contentFileGroups);
                FrameworkSpecificGroup compatibleBuildFilesGroup =
                    MSBuildNuGetProjectSystemUtility.GetMostCompatibleGroup(packageTargetFramework, buildFileGroups);

                // TODO: Need to handle References element??

                // Step-4: Raise PackageUninstalling event
                if (PackageUninstalling != null)
                {
                    PackageUninstalling(this, packageEventArgs);
                }
                PackageEventsProvider.Instance.NotifyUninstalling(packageEventArgs);

                // Step-5: Uninstall package from packages.config
                await PackagesConfigNuGetProject.UninstallPackageAsync(packageIdentity, nuGetProjectContext, token);

                // Step-6: Remove packages.config from MSBuildNuGetProject if there are no packages
                //         OR Add it again (to ensure that Source Control works), when there are some packages
                if (!(await PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).Any())
                {
                    MSBuildNuGetProjectSystem.RemoveFile(Path.GetFileName(PackagesConfigNuGetProject.FullPath));
                }
                else
                {
                    MSBuildNuGetProjectSystem.AddExistingFile(Path.GetFileName(PackagesConfigNuGetProject.FullPath));
                }

                // Step-7: Uninstall package from the msbuild project
                // Step-7.1: Remove references
                if (MSBuildNuGetProjectSystemUtility.IsValid(compatibleReferenceItemsGroup))
                {
                    foreach (var item in compatibleReferenceItemsGroup.Items)
                    {
                        if (IsAssemblyReference(item))
                        {
                            MSBuildNuGetProjectSystem.RemoveReference(Path.GetFileName(item));
                        }
                    }
                }

                // Step-7.2: Framework references are never removed. This is a no-op

                // Step-7.3: Remove content files
                if (MSBuildNuGetProjectSystemUtility.IsValid(compatibleContentFilesGroup))
                {
                    MSBuildNuGetProjectSystemUtility.DeleteFiles(MSBuildNuGetProjectSystem,
                                                                 zipArchive,
                                                                 (await GetInstalledPackagesAsync(token)).Select(pr => FolderNuGetProject.GetInstalledPackageFilePath(pr.PackageIdentity)),
                                                                 compatibleContentFilesGroup,
                                                                 FileTransformers);
                }

                // Step-7.4: Remove build imports
                if (MSBuildNuGetProjectSystemUtility.IsValid(compatibleBuildFilesGroup))
                {
                    foreach (var buildImportFile in compatibleBuildFilesGroup.Items)
                    {
                        string fullImportFilePath = Path.Combine(FolderNuGetProject.GetInstalledPath(packageIdentity), buildImportFile);
                        MSBuildNuGetProjectSystem.RemoveImport(fullImportFilePath);
                    }
                }

                // Step-7.5: Remove binding redirects. This is a no-op

                // Step-8: Raise PackageReferenceRemoved event
                if (PackageReferenceRemoved != null)
                {
                    PackageReferenceRemoved(this, packageEventArgs);
                }
                PackageEventsProvider.Instance.NotifyReferenceRemoved(packageEventArgs);

                // Step-9: Execute powershell script - uninstall.ps1
                IEnumerable <FrameworkSpecificGroup> toolItemGroups = packageReader.GetToolItems();
                FrameworkSpecificGroup compatibleToolItemsGroup     = MSBuildNuGetProjectSystemUtility.GetMostCompatibleGroup(MSBuildNuGetProjectSystem.TargetFramework,
                                                                                                                              toolItemGroups);
                if (MSBuildNuGetProjectSystemUtility.IsValid(compatibleToolItemsGroup))
                {
                    string uninstallPS1RelativePath = compatibleToolItemsGroup.Items.Where(p =>
                                                                                           p.EndsWith(Path.DirectorySeparatorChar + PowerShellScripts.Uninstall)).FirstOrDefault();
                    if (!String.IsNullOrEmpty(uninstallPS1RelativePath))
                    {
                        string packageInstallPath = FolderNuGetProject.GetInstalledPath(packageIdentity);
                        await MSBuildNuGetProjectSystem.ExecuteScriptAsync(packageInstallPath, uninstallPS1RelativePath, zipArchive, this);
                    }
                }
            }

            // Step-10: Uninstall package from the folderNuGetProject
            await FolderNuGetProject.UninstallPackageAsync(packageIdentity, nuGetProjectContext, token);

            // Step-11: Raise PackageUninstalled event
            if (PackageUninstalled != null)
            {
                PackageUninstalled(this, packageEventArgs);
            }
            PackageEventsProvider.Instance.NotifyUninstalled(packageEventArgs);

            return(true);
        }
示例#27
0
        /// <summary>
        /// 从文件中加载插件并管理(但不初始化)
        /// </summary>
        /// <param name="fileName">相对于运行目录的文件名</param>
        public async Task LoadPackageAsync(string fileName)
        {
            using PackageArchiveReader reader = new PackageArchiveReader(File.OpenRead(fileName), false);
            NuspecReader nuspecReader = await reader.GetNuspecReaderAsync(CancellationToken.None);

            string identity = nuspecReader.GetId();
            IEnumerable <FrameworkSpecificGroup> groups = await reader.GetLibItemsAsync(CancellationToken.None);

            FrameworkSpecificGroup group = groups.Where(x => x.TargetFramework.GetShortFolderName().StartsWith("netstandard")).OrderByDescending(x => x.TargetFramework.GetShortFolderName()).FirstOrDefault();

            foreach (string packageFile in group.Items)
            {
                if (!packageFile.EndsWith(".dll"))
                {
                    continue;
                }

                string tmpPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
                string path    = reader.ExtractFile(packageFile, tmpPath, NullLogger.Instance);
                //Type type = Load(await File.ReadAllBytesAsync(path));
                Type type = Load(path);
                if (type != null)// 为null时则不是插件程序集, 但不一定不是依赖程序集
                {
                    PluginContext context = new PluginContext();
                    PluginMeta    meta    = new PluginMeta(identity, fileName, Path.Combine(Environment.CurrentDirectory, "plugins", identity));
                    context.Meta = meta;
                    if (!Directory.Exists(meta.SpaceDirectory))
                    {
                        Directory.CreateDirectory(meta.SpaceDirectory);
                        FrameworkSpecificGroup item = (await reader.GetContentItemsAsync(CancellationToken.None)).FirstOrDefault();
                        if (item != null)
                        {
                            foreach (string file in item.Items)
                            {
                                if (file.EndsWith('/') || file.EndsWith('\\'))
                                {
                                    continue;
                                }

                                ZipArchiveEntry entry = reader.GetEntry(file);
                                entry.SaveAsFile(Path.Combine(meta.SpaceDirectory, file.Substring(8)), NullLogger.Instance);
                            }
                        }
                    }
                    string configFile = Path.Combine(meta.SpaceDirectory, "config.json");
                    if (File.Exists(configFile))
                    {
                        context.Configuration = new Lazy <IConfiguration>(() =>
                        {
                            ConfigurationBuilder builder = new ConfigurationBuilder();
                            builder.AddJsonFile(configFile);
                            return(builder.Build());
                        });
                    }
                    else
                    {
                        context.Configuration = new Lazy <IConfiguration>(() => (new ConfigurationBuilder().Build()));
                    }
                    string dataFile = Path.Combine(meta.SpaceDirectory, "data.db");
                    context.Repository = new Lazy <IRepository>(() => new LiteDbRepository(new LiteDatabase(dataFile)));
                    plugins.Add(type, context);
                }
            }
        }
示例#28
0
        private static bool IsValid(FrameworkSpecificGroup frameworkSpecificGroup)
        {
            if (frameworkSpecificGroup != null)
            {
                return (frameworkSpecificGroup.HasEmptyFolder
                     || frameworkSpecificGroup.Items.Any()
                     || !frameworkSpecificGroup.TargetFramework.Equals(NuGetFramework.AnyFramework));
            }

            return false;
        }
示例#29
0
        private static FrameworkSpecificGroup Normalize(FrameworkSpecificGroup group)
        {
            // Default to returning the same group
            FrameworkSpecificGroup result = group;

            // If the group is null or it does not contain any items besides _._ then this is a no-op.
            // If it does have items create a new normalized group to replace it with.
            if (group?.Items.Any() == true)
            {
                // Filter out invalid files
                IEnumerable<string> normalizedItems = GetValidPackageItems(group.Items)
                    .Select(PathUtility.ReplaceAltDirSeparatorWithDirSeparator);

                // Create a new group
                result = new FrameworkSpecificGroup(group.TargetFramework, normalizedItems);
            }

            return result;
        }
 public bool IsPassed(FrameworkSpecificGroup group)
 => group.TargetFramework.IsAny;
示例#31
0
 internal static bool IsValid(FrameworkSpecificGroup frameworkSpecificGroup)
 {
     return(frameworkSpecificGroup != null && frameworkSpecificGroup.Items != null &&
            (frameworkSpecificGroup.Items.Any() || !frameworkSpecificGroup.TargetFramework.Equals(NuGetFramework.AnyFramework)));
 }
示例#32
0
        internal static void DeleteFiles(IMSBuildNuGetProjectSystem projectSystem,
                                         ZipArchive zipArchive,
                                         IEnumerable <string> otherPackagesPath,
                                         FrameworkSpecificGroup frameworkSpecificGroup,
                                         IDictionary <FileTransformExtensions, IPackageFileTransformer> fileTransformers)
        {
            var packageTargetFramework = frameworkSpecificGroup.TargetFramework;
            IPackageFileTransformer transformer;

            try
            {
                projectSystem.BeginProcessing();


                var directoryLookup = frameworkSpecificGroup.Items.ToLookup(
                    p => Path.GetDirectoryName(ResolveTargetPath(projectSystem,
                                                                 fileTransformers,
                                                                 fte => fte.UninstallExtension,
                                                                 GetEffectivePathForContentFile(packageTargetFramework, p),
                                                                 out transformer)));

                // Get all directories that this package may have added
                var directories = from grouping in directoryLookup
                                  from directory in FileSystemUtility.GetDirectories(grouping.Key, altDirectorySeparator: false)
                                  orderby directory.Length descending
                                  select directory;

                string projectFullPath = projectSystem.ProjectFullPath;

                // Remove files from every directory
                foreach (var directory in directories)
                {
                    var directoryFiles = directoryLookup.Contains(directory) ? directoryLookup[directory] : Enumerable.Empty <string>();

                    if (!Directory.Exists(Path.Combine(projectFullPath, directory)))
                    {
                        continue;
                    }

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

                        // Resolve the path
                        var path = ResolveTargetPath(projectSystem,
                                                     fileTransformers,
                                                     fte => fte.UninstallExtension,
                                                     GetEffectivePathForContentFile(packageTargetFramework, file),
                                                     out transformer);

                        if (projectSystem.IsSupportedFile(path))
                        {
                            // Register the file being uninstalled (used by web site project system).
                            projectSystem.RegisterProcessedFiles(new[] { path });

                            if (transformer != null)
                            {
                                // TODO: use the framework from packages.config instead of the current framework
                                // which may have changed during re-targeting
                                var projectFramework = projectSystem.TargetFramework;

                                var matchingFiles = new List <InternalZipFileInfo>();
                                foreach (var otherPackagePath in otherPackagesPath)
                                {
                                    using (var otherPackageZipReader = new PackageArchiveReader(otherPackagePath))
                                    {
                                        // use the project framework to find the group that would have been installed
                                        var mostCompatibleContentFilesGroup = GetMostCompatibleGroup(
                                            projectFramework,
                                            otherPackageZipReader.GetContentItems());

                                        if (IsValid(mostCompatibleContentFilesGroup))
                                        {
                                            // Should not normalize content files group.
                                            // It should be like a ZipFileEntry with a forward slash.
                                            foreach (var otherPackageItem in mostCompatibleContentFilesGroup.Items)
                                            {
                                                if (GetEffectivePathForContentFile(packageTargetFramework, otherPackageItem)
                                                    .Equals(GetEffectivePathForContentFile(packageTargetFramework, file), StringComparison.OrdinalIgnoreCase))
                                                {
                                                    matchingFiles.Add(new InternalZipFileInfo(otherPackagePath, otherPackageItem));
                                                }
                                            }
                                        }
                                    }
                                }

                                try
                                {
                                    var zipArchiveFileEntry = PathUtility.GetEntry(zipArchive, file);
                                    if (zipArchiveFileEntry != null)
                                    {
                                        transformer.RevertFile(zipArchiveFileEntry.Open, path, matchingFiles, projectSystem);
                                    }
                                }
                                catch (Exception e)
                                {
                                    projectSystem.NuGetProjectContext.Log(MessageLevel.Warning, e.Message);
                                }
                            }
                            else
                            {
                                try
                                {
                                    var zipArchiveFileEntry = PathUtility.GetEntry(zipArchive, file);
                                    if (zipArchiveFileEntry != null)
                                    {
                                        DeleteFileSafe(path, zipArchiveFileEntry.Open, projectSystem);
                                    }
                                }
                                catch (Exception e)
                                {
                                    projectSystem.NuGetProjectContext.Log(MessageLevel.Warning, e.Message);
                                }
                            }
                        }
                    }

                    // If the directory is empty then delete it
                    if (!GetFilesSafe(projectSystem, directory).Any() &&
                        !GetDirectoriesSafe(projectSystem, directory).Any())
                    {
                        DeleteDirectorySafe(projectSystem, directory);
                    }
                }
            }
            finally
            {
                projectSystem.EndProcessing();
            }
        }
示例#33
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();
            }
        }
        internal static void AddFiles(IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem,
                                        ZipArchive zipArchive,
                                        FrameworkSpecificGroup frameworkSpecificGroup,
                                        IDictionary<FileTransformExtensions, IPackageFileTransformer> fileTransformers)
        {
            var packageTargetFramework = frameworkSpecificGroup.TargetFramework;

            // Content files are maintained with AltDirectorySeparatorChar
            List<string> packageItemListAsArchiveEntryNames = frameworkSpecificGroup.Items.Select(i => PathUtility.ReplaceDirSeparatorWithAltDirSeparator(i)).ToList();

            packageItemListAsArchiveEntryNames.Sort(new PackageItemComparer());
            try
            {
                var zipArchiveEntryList = packageItemListAsArchiveEntryNames.Select(i => zipArchive.GetEntry(i)).Where(i => i != null).ToList();
                try
                {
                    var paths = zipArchiveEntryList.Select(file => ResolvePath(fileTransformers, fte => fte.InstallExtension,
                        GetEffectivePathForContentFile(packageTargetFramework, file.FullName)));
                    paths = paths.Where(p => !String.IsNullOrEmpty(p));
                    msBuildNuGetProjectSystem.BeginProcessing(paths);
                }
                catch (Exception)
                {
                    // Ignore all exceptions for now
                }

                foreach (ZipArchiveEntry zipArchiveEntry in zipArchiveEntryList)
                {
                    if (zipArchiveEntry == null)
                    {
                        throw new ArgumentNullException("zipArchiveEntry");
                    }

                    if (IsEmptyFolder(zipArchiveEntry.FullName))
                    {
                        continue;
                    }

                    var effectivePathForContentFile = GetEffectivePathForContentFile(packageTargetFramework, zipArchiveEntry.FullName);

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

                    if (msBuildNuGetProjectSystem.IsSupportedFile(path))
                    {
                        if (installTransformer != null)
                        {
                            installTransformer.TransformFile(zipArchiveEntry, path, msBuildNuGetProjectSystem);
                        }
                        else
                        {
                            // Ignore uninstall transform file during installation
                            string truncatedPath;
                            IPackageFileTransformer uninstallTransformer =
                                FindFileTransformer(fileTransformers, fte => fte.UninstallExtension, effectivePathForContentFile, out truncatedPath);
                            if (uninstallTransformer != null)
                            {
                                continue;
                            }
                            TryAddFile(msBuildNuGetProjectSystem, path, zipArchiveEntry.Open);
                        }
                    }
                }
            }
            finally
            {
                msBuildNuGetProjectSystem.EndProcessing();
            }
        }
 internal static bool IsValid(FrameworkSpecificGroup frameworkSpecificGroup)
 {
     return (frameworkSpecificGroup != null && frameworkSpecificGroup.Items != null &&
         (frameworkSpecificGroup.Items.Any() || !frameworkSpecificGroup.TargetFramework.Equals(NuGetFramework.AnyFramework)));
 }