Esempio n. 1
0
        public LocalPackageInfo AddPackage(LocalPackageInfo package)
        {
            var ct              = CancellationToken.None;
            var destPackageDir  = _pathResolver.GetPackageDirectory(package.Identity.Id, package.Identity.Version);
            var destPackagePath = _pathResolver.GetPackageFilePath(package.Identity.Id, package.Identity.Version);

            _fileSystem.MakeDirectoryForFile(destPackagePath);
            using (var downloader = new LocalPackageArchiveDownloader(package.Path, package.Identity, _logAdapter)) {
                downloader.CopyNupkgFileToAsync(destPackagePath, ct).Wait();
                var hashFilePath = Path.ChangeExtension(destPackagePath, PackagingCoreConstants.HashFileExtension);
                var hash         = downloader.GetPackageHashAsync("SHA512", ct).Result;
                var hashBytes    = Encoding.UTF8.GetBytes(hash);
                _fileSystem.AddFile(hashFilePath, hashFileStream => { hashFileStream.Write(hashBytes, 0, hashBytes.Length); });

                var nuspecPath = _pathResolver.GetManifestFilePath(package.Identity.Id, package.Identity.Version);
                using (var nuspecStream = File.OpenWrite(nuspecPath)) {
                    using (var fs = downloader.CoreReader.GetNuspecAsync(ct).Result) {
                        fs.CopyTo(nuspecStream);
                    }
                }
                _log.DebugFormat("Saved manifest {0}", nuspecPath);
                Lazy <NuspecReader> nuspecReader = new Lazy <NuspecReader>(() => new NuspecReader(nuspecPath));
                var packageReader = new Func <PackageReaderBase>(() => new PackageArchiveReader(File.OpenRead(destPackagePath)));
                return(new LocalPackageInfo(package.Identity, destPackagePath, package.LastWriteTimeUtc, nuspecReader, packageReader));
            }
        }
Esempio n. 2
0
        private static LockFileLibrary CreateLockFileLibrary(LocalPackageInfo package, string sha512, string path, string correctedPackageName)
        {
            var lockFileLib = new LockFileLibrary();

            // package.Id is read from nuspec and it might be in wrong casing.
            // correctedPackageName should be the package name used by dependency graph and
            // it has the correct casing that runtime needs during dependency resolution.
            lockFileLib.Name    = correctedPackageName ?? package.Id;
            lockFileLib.Version = package.Version;
            lockFileLib.Type    = LibraryType.Package;
            lockFileLib.Sha512  = sha512;

            // This is the relative path, appended to the global packages folder path. All
            // of the paths in the in the Files property should be appended to this path along
            // with the global packages folder path to get the absolute path to each file in the
            // package.
            lockFileLib.Path = path;

            using (var packageReader = new PackageFolderReader(package.ExpandedPath))
            {
                // Get package files, excluding directory entries and OPC files
                // This is sorted before it is written out
                lockFileLib.Files = packageReader
                                    .GetFiles()
                                    .Where(file => IsAllowedLibraryFile(file))
                                    .ToList();
            }

            return(lockFileLib);
        }
Esempio n. 3
0
        public LocalPackageSearchMetadataFixture()
        {
            var pkgId  = new PackageIdentity("nuget.psm.test", new NuGetVersion(0, 0, 1));
            var pkg    = new SimpleTestPackageContext(pkgId.Id, pkgId.Version.ToNormalizedString());
            var nuspec = NuspecBuilder.Create()
                         .WithPackageId(pkgId.Id)
                         .WithPackageVersion(pkgId.Version.ToNormalizedString())
                         .WithIcon("icon.png")
                         .Build();

            pkg.Nuspec = XDocument.Parse(nuspec.ToString());

            _testDirectory = TestDirectory.Create();

            SimpleTestPackageUtility.CreatePackagesAsync(_testDirectory.Path, pkg).Wait();
            var pkgPath = Path.Combine(_testDirectory.Path, $"{pkgId.Id}.{pkgId.Version.ToNormalizedString()}.nupkg");
            var info    = new LocalPackageInfo(
                identity: pkgId,
                path: pkgPath,
                lastWriteTimeUtc: DateTime.UtcNow,
                nuspec: new Lazy <Packaging.NuspecReader>(() => {
                var reader = new PackageArchiveReader(pkgPath);
                return(reader.NuspecReader);
            }),
                getPackageReader: () => new PackageArchiveReader(pkgPath));

            TestData = new LocalPackageSearchMetadata(info);
        }
        public void StopDownloadPackage(LocalPackageInfo package)
        {
            lock (syncLock)
            {
                // is really downloading?
                if (!downloads.Contains(package))
                {
                    return;
                }

                // update status
                if (package.DownloadStatus.IsDownloaded)
                {
                    package.DownloadStatus.Data.SegmentsBitmap = null;
                }
                // mark as "don't resume download"
                package.DownloadStatus.Data.IsDownloading = false;
                packageRegistry.UpdateDownloadStatus(package);

                // stop
                UpdateQueue(package, isInterested: false);
            }

            DownloadStatusChange?.Invoke(new DownloadStatusChange()
            {
                Package = package, HasStopped = true
            });
        }
Esempio n. 5
0
        private void Init()
        {
            localPackages = new Dictionary <Hash, LocalPackageInfo>();

            var packageReferences = localPackageManager.ListPackages(deleteUnfinishedBuilds: true).ToArray();

            var packagesInitData = new List <LocalPackageInfo>();

            foreach (var pr in packageReferences)
            {
                PackageHashes       hashes;
                PackageDownloadInfo download;
                PackageMeta         meta;
                PackageSequenceInfo packageSequence;
                try
                {
                    hashes          = localPackageManager.ReadPackageHashesFile(pr);
                    packageSequence = hashes.CreatePackageSequence();
                    download        = localPackageManager.ReadPackageDownloadStatus(pr, packageSequence);
                    meta            = localPackageManager.ReadPackageMetadata(pr);

                    var item = new LocalPackageInfo(pr, download, hashes, meta, packageSequence);
                    packagesInitData.Add(item);
                }
                catch (Exception e)
                {
                    logger.LogWarning(e, "Can't read package {0:s}", pr.Id);
                    continue;
                }
            }

            UpdateLists(addToLocal: packagesInitData, removeFromLocal: null, addToDiscovered: Enumerable.Empty <DiscoveredPackage>());
        }
Esempio n. 6
0
        /// <summary>
        /// Add a file to the repository.
        /// </summary>
        public void AddPackage(LocalPackageInfo package)
        {
            _logger.InfoFormat("Start adding package {0} {1}.", package.Identity.Id, package.Identity.Version);

            // if (IgnoreSymbolsPackages && package.IsSymbolsPackage())
            // {
            //     var message = string.Format("Package {0} is a symbols package (it contains .pdb files and a /src folder). The server is configured to ignore symbols packages.", package);

            //     _logger.Error(message);
            //     throw new InvalidOperationException(message);
            // }

            if (!AllowOverrideExistingPackageOnPush && Exists(package.Identity.Id, package.Identity.Version))
            {
                var message = string.Format("Package {0} already exists. The server is configured to not allow overwriting packages that already exist.", package.Identity);

                _logger.Error(message);
                throw new InvalidOperationException(message);
            }

            using (LockAndSuppressFileSystemWatcher())
            {
                // Copy to correct filesystem location
                package = _expandedPackageRepository.AddPackage(package);

                // Add to metadata store
                _serverPackageStore.Store(CreateServerPackage(package, EnableDelisting));

                _logger.InfoFormat("Finished adding package {0} {1}.", package.Identity.Id, package.Identity.Version);
            }
        }
Esempio n. 7
0
        public async Task DeletePackageAsync(LocalPackageInfo packageInfo)
        {
            if (packageInfo == null)
            {
                throw new ArgumentNullException(nameof(packageInfo));
            }

            // first mark for deletion
            Task waitForReleaseLocksTask;

            lock (packagesLock)
            {
                if (packageInfo.LockProvider.IsMarkedToDelete)
                {
                    return;
                }
                waitForReleaseLocksTask = packageInfo.LockProvider.MarkForDelete();
            }

            // notify we are deleting package (stop download)
            LocalPackageDeleting?.Invoke(packageInfo);

            // wait for all resources all unlocked
            await waitForReleaseLocksTask;

            // delete content
            localPackageManager.DeletePackage(packageInfo);

            // update collections
            UpdateLists(addToLocal: null, removeFromLocal: new[] { packageInfo }, addToDiscovered: null);

            // notify we have deleted package (stop download)
            LocalPackageDeleted?.Invoke(packageInfo);
        }
        public static async Task <License> GetLicenseAsync(this LocalPackageInfo info, ILogger log = null)
        {
            var licenseUrl = info.Nuspec.GetLicenseUrl();

            if (!string.IsNullOrWhiteSpace(licenseUrl) && Uri.IsWellFormedUriString(licenseUrl, UriKind.Absolute))
            {
                var license = await new Uri(licenseUrl).GetLicenseAsync(log);
                if (license != null)
                {
                    return(license);
                }
            }

            var projectUrl = info.Nuspec.GetProjectUrl();

            if (!string.IsNullOrWhiteSpace(projectUrl) && Uri.IsWellFormedUriString(projectUrl, UriKind.Absolute))
            {
                var license = await new Uri(projectUrl).GetLicenseAsync(log);
                if (license != null)
                {
                    return(license);
                }
            }
            return(null);
        }
        public void InterestedInPackage(LocalPackageInfo packageInfo)
        {
            logger.LogDebug("Started looking for peers having: {0}", packageInfo);
            lock (syncLock)
            {
                if (states.ContainsKey(packageInfo.Id))
                {
                    return;                                     // already there
                }
                var status = new PackagePeersStatus(loggerFactory.CreateLogger <PackagePeersStatus>(), packageInfo);
                states.Add(packageInfo.Id, status);

                // add status for each peer that knows package
                int alreadyFound = 0;
                foreach (var peer in peers.Values)
                {
                    if (!peer.PeerInfo.KnownPackages.TryGetValue(packageInfo.Id, out PackageStatus ps))
                    {
                        continue;
                    }
                    alreadyFound++;
                    status.AddPeer(peer, isSeeder: ps.IsSeeder);
                }
            }

            // update status if needed
            TryRunStatusCallbackNow();
        }
Esempio n. 10
0
        private async Task DeletePackage(LocalPackageInfo package, NuGetFramework projectFramework, string installPath, ILogger logger, CancellationToken token)
        {
            logger.LogInformation($"Deleting package '{package.Identity}'.");
            using (var packageReader = package.GetReader())
            {
                foreach (var plugin in PackageManagerPlugins)
                {
                    var accepted = await plugin.OnPackageUninstallingAsync(package.Identity, projectFramework, packageReader, installPath);
                    if (!accepted) continue;
                }

                foreach (var file in await packageReader.GetPackageFilesAsync(PackageSaveMode, token))
                {
                    var path = Path.Combine(installPath, file);
                    FileUtility.Delete(path);
                }
            }

            FileUtility.Delete(package.Path);
            var installTree = new DirectoryInfo(installPath);
            DeleteDirectoryTree(installTree);
            foreach (var plugin in PackageManagerPlugins)
            {
                await plugin.OnPackageUninstalledAsync(package.Identity, projectFramework, null, installPath);
            }
        }
Esempio n. 11
0
        private void ProcessArchiveForNuGetAPIsUsedInScripts(LocalPackageInfo packageInfo)
        {
            using (var archive = ZipFile.Open(packageInfo.Path, ZipArchiveMode.Read))
            {
                var scriptFiles = archive.Entries
                                  .Where(e => e.FullName.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase) || e.FullName.EndsWith(".psm1", StringComparison.OrdinalIgnoreCase));

                if (scriptFiles.Count() > 0)
                {
                    var packageIdentity = packageInfo.Identity;
                    var pathResolver    = new VersionFolderPathResolver(_outputPath);
                    var writeDir        = Path.Combine(_outputPath, pathResolver.GetPackageDirectory(packageIdentity.Id, packageIdentity.Version));
                    Directory.CreateDirectory(writeDir);

                    foreach (var scriptFile in scriptFiles)
                    {
                        var path = Path.Combine(writeDir, Guid.NewGuid().ToString() + scriptFile.Name);
                        scriptFile.ExtractToFile(path, true);

                        using (var stream = scriptFile.Open())
                            using (var reader = new StreamReader(stream))
                            {
                                var scriptFileContent = reader.ReadToEnd();
                                if (scriptFileContent.Contains("NuGet.VisualStudio.IFileSystemProvider") ||
                                    scriptFileContent.Contains("NuGet.VisualStudio.ISolutionManager"))
                                {
                                    AddToPackageCollection(packageIdentity, scriptFile.FullName, "");
                                }
                            }
                    }
                }
            }
        }
Esempio n. 12
0
        public static string GetPackageAssemblySearchPath(
            LocalPackageInfo packageInfo,
            NuGetFramework framework)
        {
            if (packageInfo == null)
            {
                return(null);
            }

            if (framework == null)
            {
                throw new ArgumentNullException(nameof(framework));
            }

            var possibleFrameworks = packageInfo.Files
                                     .Select(path => path.Split(new [] { '/', '\\' }))
                                     .Where(parts => string.Equals(parts [0], "lib", StringComparison.OrdinalIgnoreCase))
                                     .Select(parts => NuGetFramework.ParseFolder(parts [1].ToLowerInvariant()))
                                     .Distinct();

            var bestFramework = new FrameworkReducer()
                                .GetNearest(framework, possibleFrameworks);

            return(Path.Combine(
                       packageInfo.ExpandedPath,
                       "lib",
                       bestFramework.GetShortFolderName()));
        }
Esempio n. 13
0
        private static LockFileLibrary CreateLockFileLibrary(LocalPackageInfo package, string sha512, string path)
        {
            var lockFileLib = new LockFileLibrary();

            lockFileLib.Name    = package.Id;
            lockFileLib.Version = package.Version;
            lockFileLib.Type    = LibraryType.Package;
            lockFileLib.Sha512  = sha512;

            // This is the relative path, appended to the global packages folder path. All
            // of the paths in the in the Files property should be appended to this path along
            // with the global packages folder path to get the absolute path to each file in the
            // package.
            lockFileLib.Path = path;

            using (var packageReader = new PackageFolderReader(package.ExpandedPath))
            {
                // Get package files, excluding directory entries and OPC files
                // This is sorted before it is written out
                lockFileLib.Files = packageReader
                                    .GetFiles()
                                    .Where(file => IsAllowedLibraryFile(file))
                                    .ToList();
            }

            return(lockFileLib);
        }
Esempio n. 14
0
        private LocalPackageInfo FindCandidate(string name, NuGetVersionRange versionRange)
        {
            var packages = _repository.FindPackagesById(name);

            if (versionRange == null)
            {
                // TODO: Disallow null versions for nuget packages
                var packageInfo = packages.FirstOrDefault();
                if (packageInfo != null)
                {
                    return(packageInfo);
                }

                return(null);
            }

            LocalPackageInfo bestMatch = null;

            foreach (var packageInfo in packages)
            {
                if (versionRange.IsBetter(
                        current: bestMatch?.Version,
                        considering: packageInfo.Version))
                {
                    bestMatch = packageInfo;
                }
            }

            if (bestMatch == null)
            {
                return(null);
            }

            return(bestMatch);
        }
        public Dictionary <string, string> Execute(ZipArchive archive, LocalPackageInfo localPackage)
        {
            var results = new Dictionary <string, string>();;

            var ps1Files = archive.Entries
                           .Where(e => e.FullName.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase))
                           .ToArray();

            var ps1FilesContainingNuGetAPIs = new List <string>();

            if (ps1Files.Count() > 0)
            {
                foreach (var scriptFile in ps1Files)
                {
                    var path = GetRandomPath();
                    scriptFile.ExtractToFile(path, true);

                    using (var stream = scriptFile.Open())
                        using (var reader = new StreamReader(stream))
                        {
                            var scriptFileContent = reader.ReadToEnd();
                            if (scriptFileContent.Contains("NuGet.VisualStudio.IFileSystemProvider") ||
                                scriptFileContent.Contains("NuGet.VisualStudio.ISolutionManager"))
                            {
                                ps1FilesContainingNuGetAPIs.Add(scriptFile.FullName);
                            }
                        }
                }
            }

            results.Add(Constants.PS1ScriptsWithNuGetAPIs, string.Join(";", ps1FilesContainingNuGetAPIs));
            return(results);
        }
Esempio n. 16
0
        private static LockFileLibrary CreateLockFileLibrary(LocalPackageInfo package, string sha512, string path)
        {
            var lockFileLib = new LockFileLibrary
            {
                Name    = package.Id,
                Version = package.Version,
                Type    = LibraryType.Package,
                Sha512  = sha512,

                // This is the relative path, appended to the global packages folder path. All
                // of the paths in the in the Files property should be appended to this path along
                // with the global packages folder path to get the absolute path to each file in the
                // package.
                Path = path
            };

            foreach (var file in package.Files)
            {
                if (!lockFileLib.HasTools && HasTools(file))
                {
                    lockFileLib.HasTools = true;
                }
                lockFileLib.Files.Add(file);
            }

            return(lockFileLib);
        }
Esempio n. 17
0
        /// <summary>
        /// Get a ContentItemCollection of the package files.
        /// </summary>
        /// <remarks>Library is optional.</remarks>
        public ContentItemCollection GetContentItems(LockFileLibrary library, LocalPackageInfo package)
        {
            if (package == null)
            {
                throw new ArgumentNullException(nameof(package));
            }

            var identity = new PackageIdentity(package.Id, package.Version);

            if (!_contentItems.TryGetValue(identity, out var collection))
            {
                collection = new ContentItemCollection();

                if (library == null)
                {
                    // Read folder
                    collection.Load(package.Files);
                }
                else
                {
                    // Use existing library
                    collection.Load(library.Files);
                }

                _contentItems.Add(identity, collection);
            }

            return(collection);
        }
        private IEnumerable <string> GetAssembliesForFramework(LocalPackageInfo package, NuGetFramework framework, IEnumerable <string> files)
        {
            var contentItems = new NuGet.ContentModel.ContentItemCollection();
            HashSet <string> referenceFilter = null;

            contentItems.Load(files);

            // This will throw an appropriate error if the nuspec is missing
            var            nuspec = package.Nuspec;
            IList <string> compileTimeAssemblies = null;
            IList <string> runtimeAssemblies     = null;

            var referenceSet = nuspec.GetReferenceGroups().GetNearest(framework);

            if (referenceSet != null)
            {
                referenceFilter = new HashSet <string>(referenceSet.Items, StringComparer.OrdinalIgnoreCase);
            }

            var conventions     = new ManagedCodeConventions(null);
            var managedCriteria = conventions.Criteria.ForFramework(framework);
            var compileGroup    = contentItems.FindBestItemGroup(managedCriteria, conventions.Patterns.CompileAssemblies, conventions.Patterns.RuntimeAssemblies);

            if (compileGroup != null)
            {
                compileTimeAssemblies = compileGroup.Items.Select(t => t.Path).ToList();
            }

            var runtimeGroup = contentItems.FindBestItemGroup(managedCriteria, conventions.Patterns.RuntimeAssemblies);

            if (runtimeGroup != null)
            {
                runtimeAssemblies = runtimeGroup.Items.Select(p => p.Path).ToList();
            }

            // COMPAT: Support lib/contract so older packages can be consumed
            var contractPath = "lib/contract/" + package.Id + ".dll";
            var hasContract  = files.Any(path => path == contractPath);
            var hasLib       = runtimeAssemblies?.Any();

            if (hasContract &&
                hasLib.HasValue &&
                hasLib.Value &&
                !framework.IsDesktop())
            {
                compileTimeAssemblies.Clear();
                compileTimeAssemblies.Add(contractPath);
            }

            // Apply filters from the <references> node in the nuspec
            if (referenceFilter != null)
            {
                // Remove anything that starts with "lib/" and is NOT specified in the reference filter.
                // runtimes/* is unaffected (it doesn't start with lib/)
                compileTimeAssemblies = compileTimeAssemblies.Where(p => !p.StartsWith("lib/") || referenceFilter.Contains(Path.GetFileName(p))).ToList();
            }

            return(compileTimeAssemblies ?? Enumerable.Empty <string>());
        }
Esempio n. 19
0
        private static XElement GeneratePackagePathProperty(LocalPackageInfo localPackageInfo)
        {
#if NETCOREAPP
            return(GenerateProperty($"Pkg{localPackageInfo.Id.Replace(".", "_", StringComparison.Ordinal)}", localPackageInfo.ExpandedPath));
#else
            return(GenerateProperty($"Pkg{localPackageInfo.Id.Replace(".", "_")}", localPackageInfo.ExpandedPath));
#endif
        }
Esempio n. 20
0
        public static LockFileTargetLibrary CreateLockFileTargetLibrary(
            LockFileLibrary library,
            LocalPackageInfo package,
            RestoreTargetGraph targetGraph,
            LibraryIncludeFlags dependencyType,
            NuGetFramework targetFrameworkOverride,
            IEnumerable <LibraryDependency> dependencies)
        {
            LockFileTargetLibrary lockFileLib = null;

            var framework         = targetFrameworkOverride ?? targetGraph.Framework;
            var runtimeIdentifier = targetGraph.RuntimeIdentifier;

            // Read files from package
            var files        = GetPackageFiles(library, package);
            var contentItems = new ContentItemCollection();

            contentItems.Load(files);

            // This will throw an appropriate error if the nuspec is missing
            var nuspec = package.Nuspec;

            // Create fallback criteria, this will always be one or more.
            var orderedCriteriaSets = CreateOrderedCriteriaSets(targetGraph, framework);

            for (var i = 0; i < orderedCriteriaSets.Count; i++)
            {
                // Create a new library each time to avoid
                // assets being added from other criteria.
                lockFileLib = new LockFileTargetLibrary()
                {
                    Name    = package.Id,
                    Version = package.Version,
                    Type    = LibraryType.Package
                };

                // Populate assets
                AddAssets(library, package, targetGraph, dependencyType, lockFileLib, framework, runtimeIdentifier, files, contentItems, nuspec, orderedCriteriaSets[i]);

                // Check if compatile assets were found.
                // If no compatible assets were found and this is the last check
                // continue on with what was given, this will fail in the normal
                // compat verification.
                if (CompatibilityChecker.HasCompatibleAssets(lockFileLib))
                {
                    // Stop when compatible assets are found.
                    break;
                }
            }

            // Add dependencies
            AddDependencies(dependencies, lockFileLib, framework, nuspec);

            // Exclude items
            ExcludeItems(lockFileLib, dependencyType);

            return(lockFileLib);
        }
Esempio n. 21
0
        public ServerPackage CreateServerPackage(LocalPackageInfo package, bool enableDelisting)
        {
            // File names
            var packageFileName = package.Path;
            var hashFileName    = Path.ChangeExtension(packageFileName, PackagingCoreConstants.HashFileExtension);

            // File system
            var physicalFileSystem = _fileSystem as PhysicalFileSystem;

            // Build package info
            var packageDerivedData = new PackageDerivedData();

            // Read package hash
            using (var reader = new StreamReader(_fileSystem.OpenFile(hashFileName)))
            {
                packageDerivedData.PackageHash = reader.ReadToEnd().Trim();
            }

            // Read package info
            var localPackage = package;

            if (physicalFileSystem != null)
            {
                // Read package info from file system
                var fileInfo = new FileInfo(packageFileName);
                packageDerivedData.PackageSize = fileInfo.Length;

                packageDerivedData.LastUpdated = _fileSystem.GetLastModified(packageFileName);
                packageDerivedData.Created     = _fileSystem.GetCreated(packageFileName);
                packageDerivedData.Path        = packageFileName;
                packageDerivedData.FullPath    = fileInfo.FullName;

                // if (enableDelisting && localPackage != null)
                // {
                //     // hidden packages are considered delisted
                //     localPackage.Listed = !fileInfo.Attributes.HasFlag(FileAttributes.Hidden);
                // }
            }
            else
            {
                throw new NotSupportedException("Read package info from package (slower)");
                // FIXME Read package info from package (slower)
                // using (var stream = package.GetStream())
                // {
                //     packageDerivedData.PackageSize = stream.Length;
                // }

                // packageDerivedData.LastUpdated = DateTime.MinValue;
                // packageDerivedData.Created = DateTime.MinValue;
            }

            // TODO: frameworks?

            // Build entry
            var serverPackage = new ServerPackage(package.Nuspec, packageDerivedData);

            return(serverPackage);
        }
Esempio n. 22
0
        public bool IsPackageInstalled(LocalPackageInfo package)
        {
            var packagePathResolver = new NuGet.Packaging.PackagePathResolver(Packagesfolder);
            var installedPath       = packagePathResolver.GetInstalledPath(package.Identity);

            PackageReaderBase packageReader;

            packageReader = new PackageFolderReader(installedPath);
            var libItems         = packageReader.GetLibItems();
            var frameworkReducer = new FrameworkReducer();
            var nearest          = frameworkReducer.GetNearest(NuGetFramework, libItems.Select(x => x.TargetFramework));
            var files            = libItems
                                   .Where(x => x.TargetFramework.Equals(nearest))
                                   .SelectMany(x => x.Items).ToList();


            foreach (var f in files)
            {
                string source   = "";
                string f2       = "";
                string filename = "";
                string dir      = "";
                string target   = "";
                try
                {
                    source   = System.IO.Path.Combine(installedPath, f);
                    f2       = f.Substring(f.IndexOf("/", 4) + 1);
                    filename = System.IO.Path.GetFileName(f2);
                    dir      = System.IO.Path.GetDirectoryName(f2);
                    target   = System.IO.Path.Combine(Destinationfolder, dir, filename);
                    if (!System.IO.Directory.Exists(System.IO.Path.Combine(Destinationfolder, dir)))
                    {
                        System.IO.Directory.CreateDirectory(System.IO.Path.Combine(Destinationfolder, dir));
                    }
                    if (!System.IO.File.Exists(source))
                    {
                        return(false);
                    }
                    if (!System.IO.File.Exists(target))
                    {
                        return(false);
                    }
                    var infoOld = new System.IO.FileInfo(source);
                    var infoNew = new System.IO.FileInfo(target);
                    if (infoNew.LastWriteTime != infoOld.LastWriteTime)
                    {
                        return(false);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }

            return(true);
        }
        public Dictionary <string, string> Execute(ZipArchive archive, LocalPackageInfo localPackage)
        {
            var results = new Dictionary <string, string>();;

            var xdtFiles = archive.Entries.Where(e => e.FullName.EndsWith(".xdt", StringComparison.OrdinalIgnoreCase));

            results.Add(Constants.XdtFiles, string.Join(";", xdtFiles));
            return(results);
        }
Esempio n. 24
0
        public Dictionary <string, string> Execute(ZipArchive archive, LocalPackageInfo localPackage)
        {
            var results = new Dictionary <string, string>();;

            var ppFiles = archive.Entries.Where(e => e.FullName.EndsWith(".pp"));

            results.Add(Constants.PPFiles, string.Join(";", ppFiles));
            return(results);
        }
Esempio n. 25
0
 private void RegisterPackageInternal(LocalPackageInfo package)
 {
     lock (packagesLock)
     {
         if (localPackages.ContainsKey(package.Id))
         {
             throw new InvalidOperationException("Registering package with existing hash.");
         }
         UpdateLists(addToLocal: new LocalPackageInfo[] { package }, removeFromLocal: null, addToDiscovered: null);
     }
 }
Esempio n. 26
0
        public Dictionary <string, string> Execute(ZipArchive archive, LocalPackageInfo localPackage)
        {
            var msbuildFiles = archive.Entries
                               .Where(e => e.FullName.EndsWith(localPackage.Identity.Id + ".targets", StringComparison.OrdinalIgnoreCase) ||
                                      e.FullName.EndsWith(localPackage.Identity.Id + ".props", StringComparison.OrdinalIgnoreCase));

            var results = new Dictionary <string, string>();;

            results.Add(Constants.MSBuildFiles, string.Join(";", msbuildFiles));
            return(results);
        }
Esempio n. 27
0
 public bool TryGetPackage(Hash packageHash, out LocalPackageInfo package)
 {
     lock (packagesLock)
     {
         if (!localPackages.TryGetValue(packageHash, out package))
         {
             return(false);
         }
         return(true);
     }
 }
Esempio n. 28
0
 private void PrintCorruptedInstallInfo(LocalPackageInfo info)
 {
     using (Renderer.WithColor(ConsoleColor.Red))
     {
         Renderer.WriteLine($"  Installed version in {info.InstallFolder} is corrupted.");
         foreach (var file in info.Files)
         {
             Renderer.WriteLine($"  - {Controller.GetDisplayPath(file.Path)} is {file.Status}");
         }
     }
 }
Esempio n. 29
0
 public static LockFileTargetLibrary CreateLockFileTargetLibrary(
     LockFileLibrary library,
     LocalPackageInfo package,
     RestoreTargetGraph targetGraph,
     LibraryIncludeFlags dependencyType,
     NuGetFramework targetFrameworkOverride,
     IEnumerable <LibraryDependency> dependencies,
     LockFileBuilderCache cache)
 {
     return(CreateLockFileTargetLibrary(libraryDependency: null, library, package, targetGraph, dependencyType, targetFrameworkOverride, dependencies, cache));
 }
Esempio n. 30
0
        public void AddLocalPackage(PackageIdentity identity, string localPath)
        {
            var newPackage = new LocalPackageInfo(identity.Id, identity.Version.ToString(), localPath);

            if (_localPackages.Contains(newPackage, LocalPackageInfo.IdVersionComparer.New))
            {
                return;
            }

            _localPackages.Add(newPackage);
        }