Ejemplo n.º 1
0
        protected override void ProcessPackage(PackageProvider provider, IEnumerable <string> searchKey, SoftwareIdentity package)
        {
            base.ProcessPackage(provider, searchKey, package);

            // return the object to the caller now.
            WriteObject(package);

            if (IncludeDependencies)
            {
                var missingDependencies = new HashSet <string>();
                foreach (var dep in package.Dependencies)
                {
                    // note: future work may be needed if the package sources currently selected by the user don't
                    // contain the dependencies.
                    var dependendcies = PackageManagementService.FindPackageByCanonicalId(dep, this);
                    var depPkg        = dependendcies.OrderByDescending(pp => pp, SoftwareIdentityVersionComparer.Instance).FirstOrDefault();

                    if (depPkg == null)
                    {
                        missingDependencies.Add(dep);
                        Warning(Constants.Messages.UnableToFindDependencyPackage, dep);
                    }
                    else
                    {
                        ProcessPackage(depPkg.Provider, searchKey.Select(each => each + depPkg.Name).ToArray(), depPkg);
                    }
                }
                if (missingDependencies.Any())
                {
                    Error(Constants.Errors.UnableToFindDependencyPackage, missingDependencies.JoinWithComma());
                }
            }
        }
Ejemplo n.º 2
0
        private bool InstallProviderFromInstaller(Package provider, Link link, string fastPath, BootstrapRequest request)
        {
            switch (link.MediaType)
            {
            case Iso19770_2.MediaType.MsiPackage:
            case Iso19770_2.MediaType.MsuPackage:
                return(InstallPackageFile(provider, fastPath, request));

            case Iso19770_2.MediaType.PackageReference:
                // let the core figure out how to install this package
                var packages = PackageManagementService.FindPackageByCanonicalId(link.HRef.AbsoluteUri, request).ToArray();
                switch (packages.Length)
                {
                case 0:
                    request.Warning("Unable to resolve package reference '{0}'", link.HRef);
                    return(false);

                case 1:
                    return(InstallPackageReference(provider, fastPath, request, packages));

                default:
                    request.Warning("Package Reference '{0}' resolves to {1} packages.", link.HRef, packages.Length);
                    return(false);
                }

            case Iso19770_2.MediaType.NuGetPackage:
                return(InstallNugetPackage(provider, link, fastPath, request));

            default:
                request.Warning("Provider '{0}' with link '{1}' has unknown media type '{2}'.", provider.Name, link.HRef, link.MediaType);
                return(false);
            }
        }
Ejemplo n.º 3
0
        public void GetInstalledPackages(string name, string requiredVersion, string minimumVersion, string maximumVersion, BootstrapRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            request.Debug("Calling '{0}::GetInstalledPackages' '{1}','{2}','{3}','{4}'", PackageProviderName, name, requiredVersion, minimumVersion, maximumVersion);

            //search under the providerAssembies folder for the installed providers
            var providers = PackageManagementService.AllProvidersFromProviderAssembliesLocation(request).Select(providerFileAssembly => {
                //get the provider's name\version
                var versionFolder = Path.GetDirectoryName(providerFileAssembly);

                if (string.IsNullOrWhiteSpace(versionFolder))
                {
                    return(null);
                }

                Version ver;
                if (!Version.TryParse(Path.GetFileName(versionFolder), out ver))
                {
                    //this will cover whether the providerFileAssembly is at top level as well as a bad version folder
                    //skip if the provider is at the top level as they are imported already via LoadProviders() during the initialization.
                    //the provider will be handled PackageManagementService.DynamicProviders below.
                    return(null);
                }

                var providerNameFolder = Path.GetDirectoryName(versionFolder);
                if (!string.IsNullOrWhiteSpace(providerNameFolder))
                {
                    var providerName = Path.GetFileName(providerNameFolder);
                    if (!string.IsNullOrWhiteSpace(providerName))
                    {
                        return(new {
                            Name = providerName,
                            Version = (FourPartVersion)ver,
                            ProviderPath = providerFileAssembly
                        });
                    }
                }

                return(null);
            }).WhereNotNull();

            // return all the dynamic package providers as packages
            providers = providers.Concat(PackageManagementService.DynamicProviders.Select(each => new {
                Name = each.ProviderName,
                each.Version,
                each.ProviderPath
            })).Distinct();

            var pp = request.LocalSource.Any() ? providers.Select(each => request.GetProviderFromFile(each.ProviderPath, false, true)).WhereNotNull() :
                     providers.Select(each => request.GetProvider(each.Name, each.Version)).WhereNotNull();

            foreach (var p in pp)
            {
                request.YieldFromSwidtag(p, requiredVersion, minimumVersion, maximumVersion, name);
            }
        }
Ejemplo n.º 4
0
        public void FindPackageTest()
        {
            using (CaptureConsole) {
                var packages = Provider.FindPackage("zlib", null, null, null, new BasicHostImpl()).ToArray();

                Assert.Equal(1, packages.Length);
                var pkg1 = packages[0];

                foreach (var pkg in packages)
                {
                    Console.WriteLine("PKG (zlib?) : {0}", pkg.SwidTagText);
                }

                Assert.Equal(1, pkg1.Dependencies.Count());

                Console.WriteLine("Getting Dependencies");
                packages = PackageManagementService.FindPackageByCanonicalId(pkg1.Dependencies.FirstOrDefault(), new BasicHostImpl()).ToArray();
                Assert.Equal(1, packages.Length);

                Console.WriteLine("Processing Dependencies");

                var pkg2 = packages[0];

                foreach (var pkg in packages)
                {
                    Console.WriteLine("PKG (zlib.redist?): {0}", pkg.SwidTagText);
                }
            }
        }
Ejemplo n.º 5
0
        private bool InstallPackageReference(Package provider, string fastPath, BootstrapRequest request, SoftwareIdentity[] packages)
        {
            IHostApi installRequest = request;

            if (packages[0].Provider.Name.EqualsIgnoreCase("PowerShellGet") && !request.ProviderServices.IsElevated)
            {
                // if we're not elevated, we want powershellget to install to the user scope

                installRequest = new object[] {
                    new {
                        GetOptionKeys   = new Func <IEnumerable <string> >(() => request.OptionKeys.ConcatSingleItem("Scope")),
                        GetOptionValues = new Func <string, IEnumerable <string> >((key) => {
                            if (key != null && key.EqualsIgnoreCase("Scope"))
                            {
                                return("CurrentUser".SingleItemAsEnumerable());
                            }
                            return(request.GetOptionValues(key));
                        })
                    }
                    , installRequest
                }.As <IHostApi>();
            }

            var installing = packages[0].Provider.InstallPackage(packages[0], installRequest);

            SoftwareIdentity lastPackage = null;

            foreach (var i in installing)
            {
                lastPackage = i;
                // should we echo each package back as it comes back?
                request.YieldSoftwareIdentity(i.FastPackageReference, i.Name, i.Version, i.VersionScheme, i.Summary, i.Source, i.SearchKey, i.FullPath, i.PackageFilename);

                if (request.IsCanceled)
                {
                    installing.Cancel();
                }
            }

            if (!request.IsCanceled && lastPackage != null)
            {
                if (provider.Name.EqualsIgnoreCase("PowerShellGet"))
                {
                    // special case. PSModules we can just ask the PowerShell provider to pick it up
                    // rather than try to scan for it.
                    PackageManagementService.TryLoadProviderViaMetaProvider("PowerShell", lastPackage.FullPath, request);
                    request.YieldFromSwidtag(provider, fastPath);
                    return(true);
                }

                // looks like it installed ok.
                request.YieldFromSwidtag(provider, fastPath);

                // rescan providers
                PackageManagementService.LoadProviders(request.As <IRequest>());
                return(true);
            }
            return(false);
        }
Ejemplo n.º 6
0
        public override bool ProcessRecordAsync()
        {
            if (Stopping)
            {
                return(false);
            }

            var packageProvider = PackageManagementService.SelectProviders(ProviderName, this).FirstOrDefault();

            if (packageProvider == null)
            {
                Error(Errors.UnknownProvider, ProviderName);
                return(false);
            }

            using (var sources = CancelWhenStopped(packageProvider.ResolvePackageSources(this))) {
                // first, check if there is a source by this name already.
                var existingSources = sources.Where(each => each.IsRegistered && each.Name.Equals(Name, StringComparison.OrdinalIgnoreCase)).ToArray();

                if (existingSources.Any())
                {
                    // if there is, and the user has said -Force, then let's remove it.
                    foreach (var existingSource in existingSources)
                    {
                        if (Force)
                        {
                            if (ShouldProcess(FormatMessageString(Constants.TargetPackageSource, existingSource.Name, existingSource.Location, existingSource.ProviderName), Constants.ActionReplacePackageSource).Result)
                            {
                                using (var removedSources = CancelWhenStopped(packageProvider.RemovePackageSource(existingSource.Name, this))) {
                                    foreach (var removedSource in removedSources)
                                    {
                                        Verbose(Constants.OverwritingPackageSource, removedSource.Name);
                                    }
                                }
                            }
                        }
                        else
                        {
                            Error(Errors.PackageSourceExists, existingSource.Name);
                            return(false);
                        }
                    }
                }
            }

            if (ShouldProcess(FormatMessageString(Constants.TargetPackageSource, Name, Location, ProviderName), FormatMessageString(Constants.ActionRegisterPackageSource)).Result)
            {
                using (var added = CancelWhenStopped(packageProvider.AddPackageSource(Name, Location, Trusted, this))) {
                    foreach (var addedSource in added)
                    {
                        WriteObject(addedSource);
                    }
                }
                return(true);
            }

            return(false);
        }
Ejemplo n.º 7
0
        public IEnumerable <SoftwareIdentity> FindPackageByCanonicalId(string canonicalId, IRequest requestObject)
        {
            if (requestObject == null)
            {
                throw new ArgumentNullException("requestObject");
            }

            return(PackageManagementService.FindPackageByCanonicalId(canonicalId, requestObject));
        }
Ejemplo n.º 8
0
        private bool InstallAssemblyProvider(Package provider, Link link, string fastPath, BootstrapRequest request)
        {
            if (!Directory.Exists(request.DestinationPath))
            {
                request.Error(ErrorCategory.InvalidOperation, fastPath, Constants.Messages.DestinationPathNotSet);
                return(false);
            }

            var targetFilename = link.Attributes[Iso19770_2.Discovery.TargetFilename];

            if (string.IsNullOrWhiteSpace(targetFilename))
            {
                request.Error(ErrorCategory.InvalidOperation, fastPath, Constants.Messages.InvalidFilename);
                return(false);
            }

            targetFilename = Path.GetFileName(targetFilename);
            var targetFile = Path.Combine(request.DestinationPath, targetFilename);

            // download the file
            var file = request.DownloadAndValidateFile(provider.Name, provider._swidtag.Links.Where(each => each.Relationship == Iso19770_2.Relationship.InstallationMedia));

            if (file != null)
            {
                // looks good! let's keep it
                if (File.Exists(targetFile))
                {
                    request.Debug("Removing old file '{0}'", targetFile);
                    targetFile.TryHardToDelete();
                }

                // is that file still there?
                if (File.Exists(targetFile))
                {
                    request.Error(ErrorCategory.InvalidOperation, fastPath, Constants.Messages.UnableToRemoveFile, targetFile);
                    return(false);
                }

                request.Debug("Copying file '{0}' to '{1}'", file, targetFile);
                File.Copy(file, targetFile);
                if (File.Exists(targetFile))
                {
                    // since we only installed a single assembly, we can just ask to load that specific assembly.
                    if (PackageManagementService.TryToLoadProviderAssembly(targetFile, request))
                    {
                        // looks good to me.
                        request.YieldFromSwidtag(provider, fastPath);
                        return(true);
                    }
                }
            }
            if (file != null)
            {
                file.TryHardToDelete();
            }
            return(false);
        }
Ejemplo n.º 9
0
 protected IEnumerable <PackageProvider> SelectProviders(string[] names)
 {
     if (names.IsNullOrEmpty())
     {
         return(PackageManagementService.SelectProviders(null, this).Where(each => !each.Features.ContainsKey(Constants.AutomationOnlyFeature)));
     }
     // you can manually ask for any provider by name, if it is for automation only.
     return(names.SelectMany(each => PackageManagementService.SelectProviders(each, this))); // .Where(each => !each.Features.ContainsKey(Constants.AutomationOnlyFeature));
 }
Ejemplo n.º 10
0
        public override bool ProcessRecordAsync()
        {
            //Error out for the case where multiple provider names with any version specified
            if (((!Name.IsNullOrEmpty() && Name.Length > 1) || Name[0].ContainsWildcards()) &&
                ((RequiredVersion != null) || (MinimumVersion != null) || (MaximumVersion != null)))
            {
                Error(Constants.Errors.MultipleNamesWithVersionNotAllowed);
                return(false);
            }

            foreach (var path in Name)
            {
                var isRooted = false;

                var resolvedPath = path;

                if (!string.IsNullOrWhiteSpace(path))
                {
                    if (IsRooted(path))
                    {
                        if ((RequiredVersion != null) || (MaximumVersion != null) || (MinimumVersion != null))
                        {
                            Error(Constants.Errors.FullProviderFilePathVersionNotAllowed);
                        }

                        try {
                            ProviderInfo        provider      = null;
                            Collection <string> resolvedPaths = GetResolvedProviderPathFromPSPath(path, out provider);

                            // Ensure the path is a single path from the file system provider
                            if ((resolvedPaths.Count > 1) ||
                                (!String.Equals(provider.Name, "FileSystem", StringComparison.OrdinalIgnoreCase)))
                            {
                                Error(Constants.Errors.FilePathMustBeFileSystemPath, path);
                                return(false);
                            }
                            resolvedPath = resolvedPaths[0];

                            isRooted = true;
                        } catch (Exception ex) {
                            Error(Constants.Errors.FileNotFound, ex.Message);
                            return(true);
                        }
                    }

                    foreach (var p in PackageManagementService.ImportPackageProvider(this, resolvedPath, RequiredVersion.ToVersion(),
                                                                                     MinimumVersion.ToVersion(), MaximumVersion.ToVersion(), isRooted, Force.IsPresent))
                    {
                        WriteObject(p);
                    }
                }
            } //foreach name

            return(true);
        }
Ejemplo n.º 11
0
        protected IEnumerable <PackageProvider> SelectProviders(string name)
        {
            // you can manually ask for any provider by name, if it is for automation only.
            var result = PackageManagementService.SelectProviders(name, this).ToArray(); //.Where(each => !each.Features.ContainsKey(Constants.AutomationOnlyFeature))

            if (result.Length == 0)
            {
                Warning(Errors.UnknownProvider, name);
            }
            return(result);
        }
Ejemplo n.º 12
0
 protected IEnumerable <PackageProvider> SelectProviders(string[] names)
 {
     if (names.IsNullOrEmpty())
     {
         return(PackageManagementService.SelectProviders(null, SuppressErrorsAndWarnings).Where(each => !each.Features.ContainsKey(Microsoft.OneGet.Constants.Features.AutomationOnly)));
     }
     // you can manually ask for any provider by name, if it is for automation only.
     if (IsInvocation)
     {
         return(names.SelectMany(each => PackageManagementService.SelectProviders(each, this)));
     }
     return(names.SelectMany(each => PackageManagementService.SelectProviders(each, SuppressErrorsAndWarnings)));
 }
Ejemplo n.º 13
0
        void CreatePackageManagementService(PackageManagementOptions options)
        {
            testProject = ProjectHelper.CreateTestProject();
            fakePackageRepositoryFactory      = new FakePackageRepositoryFactory();
            fakePackageManagerFactory         = new FakePackageManagerFactory();
            fakeProjectService                = new FakePackageManagementProjectService();
            fakeOutputMessagesView            = new FakePackageManagementOutputMessagesView();
            fakeProjectService.CurrentProject = testProject;
            packageManagementService          =
                new PackageManagementService(options,
                                             fakePackageRepositoryFactory,
                                             fakePackageManagerFactory,
                                             fakeProjectService,
                                             fakeOutputMessagesView);

            installPackageHelper = new InstallPackageHelper(packageManagementService);
        }
Ejemplo n.º 14
0
        private bool ImportProvider(SoftwareIdentity[] list)
        {
            Verbose("Importing the package provider {0}", Name.JoinWithComma());

            //after the provider gets installed, we are trying to load it
            var providers = list.SelectMany(each => PackageManagementService.ImportPackageProvider(this.SuppressErrorsAndWarnings(IsProcessing), each.Name, each.Version.ToVersion(), null, null, false, true)).ToArray();

            if (providers.Any())
            {
                Verbose(Resources.Messages.ProviderImported, providers.Select(e => e.ProviderPath).JoinWithComma());
                return(true);
            }
            else
            {
                Warning(Resources.Messages.ProviderNameDifferentFromPackageName, Name.JoinWithComma());
            }
            return(false);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Do a dfs visit. returns false if a cycle is encountered. Add the packageItem to the list at the end of each visit
        /// </summary>
        /// <param name="packageItem"></param>
        /// <param name="dependencyToBeInstalled"></param>
        /// <param name="permanentlyMarked"></param>
        /// <param name="temporarilyMarked"></param>
        /// <returns></returns>
        internal bool DepthFirstVisit(SoftwareIdentity packageItem, HashSet <SoftwareIdentity> temporarilyMarked,
                                      HashSet <SoftwareIdentity> permanentlyMarked, List <SoftwareIdentity> dependencyToBeInstalled)
        {
            // dependency loop detected because the element is temporarily marked
            if (temporarilyMarked.Contains(packageItem))
            {
                return(false);
            }

            // this is permanently marked. So we don't have to visit it.
            // This is to resolve a case where we have: A->B->C and A->C. Then we need this when we visit C again from either B or A.
            if (permanentlyMarked.Contains(packageItem))
            {
                return(true);
            }

            // Mark this node temporarily so we can detect cycle.
            temporarilyMarked.Add(packageItem);

            // Visit the dependency
            foreach (var dependency in packageItem.Dependencies)
            {
                var dependencies = PackageManagementService.FindPackageByCanonicalId(dependency, this);
                var depPkg       = dependencies.OrderByDescending(pp => pp, SoftwareIdentityVersionComparer.Instance).FirstOrDefault();

                if (!DepthFirstVisit(depPkg, temporarilyMarked, permanentlyMarked, dependencyToBeInstalled))
                {
                    // if dfs returns false then we have encountered a loop
                    return(false);
                }
                // otherwise visit the next dependency
            }

            // Add the package to the list so we can install later
            dependencyToBeInstalled.Add(packageItem);

            // Done with this node so mark it permanently
            permanentlyMarked.Add(packageItem);

            // Unmark it temporarily
            temporarilyMarked.Remove(packageItem);

            return(true);
        }
Ejemplo n.º 16
0
        protected override void ProcessPackage(PackageProvider provider, IEnumerable <string> searchKey, SoftwareIdentity package)
        {
            if (WhatIf)
            {
                // grab the dependencies and return them *first*

                foreach (var dep in package.Dependencies)
                {
                    // note: future work may be needed if the package sources currently selected by the user don't
                    // contain the dependencies.
                    var dependendcies = PackageManagementService.FindPackageByCanonicalId(dep, this);
                    foreach (var depPackage in dependendcies)
                    {
                        ProcessPackage(depPackage.Provider, searchKey.Select(each => each + depPackage.Name).ToArray(), depPackage);
                    }
                }
            }
            base.ProcessPackage(provider, searchKey, package);
        }
Ejemplo n.º 17
0
        private bool InstallPackageFile(Package provider, string fastPath, BootstrapRequest request)
        {
            // we can download and verify this package and get the core to install it.
            var file = request.DownloadAndValidateFile(provider._swidtag);

            if (file != null)
            {
                // we have a valid file.
                // run the installer
                if (request.ProviderServices.Install(file, "", request))
                {
                    // it installed ok!
                    request.YieldFromSwidtag(provider, fastPath);
                    PackageManagementService.LoadProviders(request.As <IRequest>());
                    return(true);
                }
                request.Warning(Constants.Messages.FailedProviderBootstrap, fastPath);
            }
            return(false);
        }
Ejemplo n.º 18
0
        public override bool ProcessRecordAsync()
        {
            if (Name.IsNullOrEmpty())
            {
                var providers = ListAvailable.IsPresent ? PackageManagementService.GetAvailableProviders(this, Name).ReEnumerable() : SelectProviders(Name).ReEnumerable();

                var providerOrdered = providers.OrderBy(each => each.ProviderName);
                // Get all available providers
                foreach (var p in providerOrdered)
                {
                    WriteObject(p);
                }
            }
            else
            {
                ProcessProvidersFilteredByName();
            }

            return(true);
        }
Ejemplo n.º 19
0
        protected IEnumerable <PackageProvider> SelectProviders(string name)
        {
            // you can manually ask for any provider by name, if it is for automation only.
            if (IsInvocation)
            {
                var result = PackageManagementService.SelectProviders(name, PackageManagementHost).ToArray();
                if ((result.Length == 0) && ShouldLogError)
                {
                    Error(Constants.Errors.UnknownProvider, name);
                }
                return(result);
            }

            var r = PackageManagementService.SelectProviders(name, PackageManagementHost.SuppressErrorsAndWarnings(IsProcessing)).ToArray();

            if ((r.Length == 0) && ShouldLogError)
            {
                Error(Constants.Errors.UnknownProvider, name);
            }
            return(r);
        }
Ejemplo n.º 20
0
        private void ProcessProvidersFilteredByName()
        {
            //Do not log error when a provider is not found in the list returned by SelectProviders(). This allows the searching continues
            //in the list of providers that are not loaded.
            ShouldLogError = false;
            var notfound = new List <string>();

            foreach (var name in Name)
            {
                var providers = ListAvailable.IsPresent ? PackageManagementService.GetAvailableProviders(this, new[] { name }).ReEnumerable() : SelectProviders(name).ReEnumerable();
                if (providers.Any())
                {
                    var providerOrdered = providers.OrderByDescending(each => each.ProviderName);

                    foreach (var provider in providerOrdered)
                    {
                        WriteObject(provider);
                    }
                }
                else
                {
                    notfound.Add(name);
                }
            }

            //Error out if the specific provider is not found
            if (notfound.Any())
            {
                if (notfound.Count == 1)
                {
                    Error(ListAvailable.IsPresent ? Constants.Errors.UnknownProvider : Constants.Errors.UnknownProviderFromActivatedList, notfound.FirstOrDefault());
                }
                else
                {
                    Error(ListAvailable.IsPresent ? Constants.Errors.UnknownProviders : Constants.Errors.UnknownProviderFromActivatedList, notfound.JoinWithComma());
                }
            }
            notfound.Clear();
        }
Ejemplo n.º 21
0
        public override bool GenerateDynamicParameters()
        {
            var packageProvider = PackageManagementService.SelectProviders(ProviderName, this).FirstOrDefault();

            if (packageProvider == null)
            {
                return(false);
            }

            // if the provider is selected, we can get package metadata keys from the provider
            foreach (var md in packageProvider.GetDynamicOptions(OptionCategory.Source, this))
            {
                if (DynamicParameterDictionary.ContainsKey(md.Name))
                {
                    // for now, we're just going to mark the existing parameter as also used by the second provider to specify it.
                    (DynamicParameterDictionary[md.Name] as CustomRuntimeDefinedParameter).Options.Add(md);
                }
                else
                {
                    DynamicParameterDictionary.Add(md.Name, new CustomRuntimeDefinedParameter(md));
                }
            }
            return(true);
        }
Ejemplo n.º 22
0
        protected override void ProcessPackage(PackageProvider provider, IEnumerable <string> searchKey, SoftwareIdentity package)
        {
            Debug("Calling ProcessPackage SearchKey = '{0}' and provider name ='{1}'", searchKey, package.ProviderName);
            try {
                base.ProcessPackage(provider, searchKey, package);

                // output to console
                WriteObject(AddPropertyToSoftwareIdentity(package));

                if (IncludeDependencies)
                {
                    var missingDependencies = new HashSet <string>();
                    foreach (var dep in package.Dependencies)
                    {
                        var dependendcies = PackageManagementService.FindPackageByCanonicalId(dep, this);
                        var depPkg        = dependendcies.OrderByDescending(pp => pp, SoftwareIdentityVersionComparer.Instance).FirstOrDefault();

                        if (depPkg == null)
                        {
                            missingDependencies.Add(dep);
                            Warning(Constants.Messages.UnableToFindDependencyPackage, dep);
                        }
                        else
                        {
                            ProcessPackage(depPkg.Provider, searchKey.Select(each => each + depPkg.Name).ToArray(), depPkg);
                        }
                    }
                    if (missingDependencies.Any())
                    {
                        Error(Constants.Errors.UnableToFindDependencyPackage, missingDependencies.JoinWithComma());
                    }
                }
            } catch (Exception ex) {
                Debug("Calling ProcessPackage {0}", ex.Message);
            }
        }
Ejemplo n.º 23
0
        public void GetInstalledPackages(string name, string requiredVersion, string minimumVersion, string maximumVersion, BootstrapRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            request.Debug("Calling '{0}::GetInstalledPackages' '{1}','{2}','{3}','{4}'", PackageProviderName, name, requiredVersion, minimumVersion, maximumVersion);

            //search under the providerAssembies folder for the installed providers
            var providers = PackageManagementService.AllProvidersFromProviderAssembliesLocation(request).Select(providerFileAssembly => {
                //get the provider's name\version
                var versionFolder = Path.GetDirectoryName(providerFileAssembly);

                if (string.IsNullOrWhiteSpace(versionFolder))
                {
                    return(null);
                }

                Version ver;
                if (!Version.TryParse(Path.GetFileName(versionFolder), out ver))
                {
                    //this will cover whether the providerFileAssembly is at top level as well as a bad version folder
                    //skip if the provider is at the top level as they are imported already via LoadProviders() during the initialization.
                    //the provider will be handled PackageManagementService.DynamicProviders below.
                    return(null);
                }

                var providerNameFolder = Path.GetDirectoryName(versionFolder);
                if (!string.IsNullOrWhiteSpace(providerNameFolder))
                {
                    var providerName = Path.GetFileName(providerNameFolder);
                    if (!string.IsNullOrWhiteSpace(providerName))
                    {
                        return(new {
                            Name = providerName,
                            Version = (FourPartVersion)ver,
                            ProviderPath = providerFileAssembly
                        });
                    }
                }

                return(null);
            }).WhereNotNull();

            // return all the dynamic package providers as packages
            providers = providers.Concat(PackageManagementService.DynamicProviders.Select(each => new {
                Name = each.ProviderName,
                each.Version,
                each.ProviderPath
            })).Distinct();

            foreach (var provider in providers)
            {
                // for each package manager, match it's name and version with the swidtag from the remote feed
                var p = request.GetProvider(provider.Name, provider.Version);
                if (p == null)
                {
                    request.Debug("Dynamic provider '{0}' from '{1}' is not listed in a bootstrap feed.", provider.Name, provider.ProviderPath);
                    // we didn't find it. It's possible that the provider is listed elsewhere.
                    // well, we'll return as much info as we have.
                    continue;
                }
                request.YieldFromSwidtag(p, requiredVersion, minimumVersion, maximumVersion, name);
            }
        }
Ejemplo n.º 24
0
 public IEnumerable <object> SelectProvidersWithFeature(string featureName, string value)
 {
     return(PackageManagementService.SelectProvidersWithFeature(featureName, value));
 }
Ejemplo n.º 25
0
        private bool InstallAssemblyProvider(Package provider, Link link, string fastPath, BootstrapRequest request, bool deleteFile = true)
        {
            request.Verbose(Resources.Messages.InstallingPackage, fastPath);

            if (!Directory.Exists(request.DestinationPath(request)))
            {
                request.Error(ErrorCategory.InvalidOperation, fastPath, Constants.Messages.DestinationPathNotSet);
                return(false);
            }


            string targetFilename = fastPath;
            string file           = fastPath;

            //source can be from install-packageprovider or can be from the pipeline
            if (!request.LocalSource.Any() && !fastPath.IsFile() && link != null)
            {
                targetFilename = link.Attributes[Iso19770_2.Discovery.TargetFilename];

                // download the file
                file = request.DownloadAndValidateFile(provider._swidtag);
            }

            if (string.IsNullOrWhiteSpace(targetFilename))
            {
                request.Error(ErrorCategory.InvalidOperation, fastPath, Constants.Messages.InvalidFilename);
                return(false);
            }

            targetFilename = Path.GetFileName(targetFilename);
            if (string.IsNullOrWhiteSpace(provider.Version))
            {
                request.Error(ErrorCategory.InvalidOperation, fastPath, Resources.Messages.MissingVersion);
                return(false);
            }

            //the provider is installing to like this folder: \WindowsPowerShell\Modules\PackageManagement\ProviderAssemblies\nuget\2.8.5.127
            //... providername\version\.dll
            var versionFolder = Path.Combine(request.DestinationPath(request), provider.Name, provider.Version);

            if (!Directory.Exists(versionFolder))
            {
                //we create it
                Directory.CreateDirectory(versionFolder);
            }

            var targetFile = Path.Combine(versionFolder, targetFilename);

            if (file != null)
            {
                try
                {
                    // looks good! let's keep it
                    if (File.Exists(targetFile))
                    {
                        request.Debug("Removing old file '{0}'", targetFile);
                        targetFile.TryHardToDelete();
                    }

                    // is that file still there?
                    if (File.Exists(targetFile))
                    {
                        request.Error(ErrorCategory.InvalidOperation, fastPath, Constants.Messages.UnableToRemoveFile, targetFile);
                        return(false);
                    }

                    request.Debug("Copying file '{0}' to '{1}'", file, targetFile);
                    try {
                        File.Copy(file, targetFile);
                    }
                    catch (Exception ex) {
                        request.Debug(ex.StackTrace);
                        return(false);
                    }

                    if (File.Exists(targetFile))
                    {
                        request.Verbose(Resources.Messages.InstalledPackage, provider.Name, targetFile);
                        request.YieldFromSwidtag(provider, fastPath);

                        //Load the provider. This is needed when a provider has dependencies. For example, if Nuget provider has a dependent foobar
                        // provider and when 'Install-PackageProvider -name NuGet', we want both NuGet and Foobar provider gets loaded.
                        PackageManagementService.LoadProviderAssembly(request, targetFile, false);
                        return(true);
                    }
                }
                finally
                {
                    if (deleteFile)
                    {
                        file.TryHardToDelete();
                    }
                }
            }

            return(false);
        }
Ejemplo n.º 26
0
 public UpdatePackageHelper(PackageManagementService packageManagementService)
 {
     this.packageManagementService = packageManagementService;
 }
Ejemplo n.º 27
0
 public InstallPackageHelper(PackageManagementService packageManagementService)
 {
     this.packageManagementService = packageManagementService;
 }
Ejemplo n.º 28
0
 public object SelectProvider(string providerName)
 {
     return(PackageManagementService.SelectProviders(providerName, Extend()).FirstOrDefault(each => each.Name.EqualsIgnoreCase(providerName)));
 }
Ejemplo n.º 29
0
        public bool RequirePackageProvider(string packageProviderName, string minimumVersion)
        {
            var pp = (_provider as PowerShellPackageProvider);

            return(PackageManagementService.RequirePackageProvider(pp == null ? Constants.ProviderNameUnknown : pp.GetPackageProviderName(), packageProviderName, minimumVersion, Extend()));
        }
Ejemplo n.º 30
0
 public IEnumerable <object> SelectProviders(string providerName)
 {
     return(PackageManagementService.SelectProviders(providerName, Extend()));
 }