示例#1
0
        internal static ProgressTracker StartProgress(ProgressTracker parentTracker, string message, NuGetRequest request)
        {
            if (request == null)
            {
                return null;
            }

            // if parent tracker is null, use 0 for parent id, else use the progressid of parent tracker
            return new ProgressTracker(request.StartProgress(parentTracker == null ? 0 : parentTracker.ProgressID, message));
        }
示例#2
0
        /// <summary>
        ///     Finds a package given a local filename
        /// </summary>
        /// <param name="file"></param>
        /// <param name="id"></param>
        /// <param name="request"></param>
        public void FindPackageByFile(string file, int id, NuGetRequest request)
        {
            // Nice-to-have put a debug message in that tells what's going on.
            request.Debug("Calling '{0}::FindPackageByFile' '{1}','{2}'", PackageProviderName, file, id);

            var pkgItem = request.GetPackageByFilePath(Path.GetFullPath(file));

            if (pkgItem != null)
            {
                request.YieldPackage(pkgItem, file);
            }
        }
        /// <summary>
        /// Uninstalls a package
        /// </summary>
        /// <param name="fastPackageReference"></param>
        /// <param name="request">An object passed in from the PackageManagement that contains functions that can be used to interact with its Provider</param>
        public void UninstallPackage(string fastPackageReference, NuGetRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            request.Debug(Resources.Messages.DebugInfoCallMethod3, PackageProviderName, "UninstallPackage", fastPackageReference);

            var pkg = request.GetPackageByFastpath(fastPackageReference);

            NuGetClient.UninstallPackage(request, pkg);
        }
示例#4
0
        public IPackage FindPackage(NuGetSearchContext findContext, NuGetRequest request)
        {
            request.Debug(Messages.DebugInfoCallMethod3, "NuGetPackageRepository", "FindPackage", findContext.PackageInfo.Id);
            NuGetSearchResult result = this.ResourceProvider.PackagesFeed.Find(findContext, request);

            if (result.Result != null)
            {
                return(result.Result.FirstOrDefault());
            }
            else
            {
                return(null);
            }
        }
        private IEnumerable <IPackage> SearchImpl(string searchTerm, NuGetRequest nugetRequest)
        {
            if (nugetRequest == null)
            {
                yield break;
            }

            nugetRequest.Debug(Resources.Messages.SearchingRepository, "LocalPackageRepository", Source);

            var files = Directory.GetFiles(Source);
            IEnumerable <IPackage> packageItems = files.Select(nugetRequest.GetPackageByFilePath).Where(pkgItem => pkgItem != null).Select(pkg => pkg.Package);

            if (nugetRequest.FilterOnTag != null)
            {
                foreach (var package in PackageFilterUtility.FilterOnTags(packageItems, nugetRequest.FilterOnTag.Value))
                {
                    yield return(package);
                }
            }
            else
            {
                foreach (IPackage package in packageItems)
                {
                    yield return(package);
                }
            }

            // look in the package source location for directories that contain nupkg files.
            var subdirs = Directory.EnumerateDirectories(Source, "*", SearchOption.AllDirectories);

            foreach (var subdir in subdirs)
            {
                var nupkgs = Directory.EnumerateFileSystemEntries(subdir, "*.nupkg", SearchOption.TopDirectoryOnly);
                packageItems = nupkgs.Select(nugetRequest.GetPackageByFilePath).Where(pkgItem => pkgItem != null).Select(pkg => pkg.Package);
                if (nugetRequest.FilterOnTag != null)
                {
                    foreach (var package in PackageFilterUtility.FilterOnTags(packageItems, nugetRequest.FilterOnTag.Value))
                    {
                        yield return(package);
                    }
                }
                else
                {
                    foreach (IPackage package in packageItems)
                    {
                        yield return(package);
                    }
                }
            }
        }
        /// <summary>
        /// Create a RequestWrapper that calls into <paramref name="request"/> with <param name="userName"> and <param name="userPassword"> credentials.
        /// </summary>
        /// <param name="request">The actual Request object.</param>
        /// <param name="credential">The NetworkCredential object.</param>
        public RequestWrapper(NuGetRequest request, NetworkCredential credential)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            this.Request = request;
            if (credential != null)
            {
                this.UserName     = credential.UserName;
                this.UserPassword = credential.SecurePassword;
            }
            this.Output = new NuGetRequestOutput(request);
        }
        public async Task <IssueResults> Nuget([FromBody] NuGetRequest nuGetRequest)
        {
            var results = await _storage.CreateAsync(CancellationToken.None);

            var request = new AnalyzeRequest
            {
                Id       = results.Id,
                Original = nuGetRequest.Original,
                Updated  = nuGetRequest.Updated
            };

            await _queue.AddAsync(request);

            return(results);
        }
        /// <summary>
        /// Installs a given package.
        /// </summary>
        /// <param name="fastPackageReference">A provider supplied identifier that specifies an exact package</param>
        /// <param name="request">An object passed in from the PackageManagement that contains functions that can be used to interact with its Provider</param>
        public void InstallPackage(string fastPackageReference, NuGetRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            request.Debug(Resources.Messages.DebugInfoCallMethod3, PackageProviderName, "InstallPackage", fastPackageReference);

            // Enforce use of TLS 1.2 when sending request
            var securityProtocol = System.Net.ServicePointManager.SecurityProtocol;

            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

            try {
                var pkgItem = request.GetPackageByFastpath(fastPackageReference);
                if (pkgItem == null)
                {
                    request.WriteError(ErrorCategory.InvalidArgument, fastPackageReference, Constants.Messages.UnableToResolvePackage);
                    return;
                }

                if ((pkgItem.PackageSource == null) || (pkgItem.PackageSource.Location == null) || (pkgItem.Package == null))
                {
                    request.Debug(Resources.Messages.VariableCheck, "PackageSource or PackageSource.Location or Package object", "null");
                    request.WriteError(ErrorCategory.ObjectNotFound, fastPackageReference, Constants.Messages.UnableToResolvePackage, pkgItem.Id);
                    return;
                }

                request.Debug(Resources.Messages.VariableCheck, "Package version", pkgItem.Version);
                request.Debug(Resources.Messages.VariableCheck, "Request's Destination", request.Destination);

                // got this far, let's install the package we came here for.
                if (!pkgItem.PackageSource.Repository.InstallPackage(new PublicObjectView(pkgItem), request))
                {
                    // package itself didn't install. Write error
                    request.WriteError(ErrorCategory.InvalidResult, pkgItem.Id, Constants.Messages.PackageFailedInstallOrDownload, pkgItem.Id, CultureInfo.CurrentCulture.TextInfo.ToLower(Constants.Install));

                    return;
                }
            } catch (Exception ex) {
                ex.Dump(request);
                request.WriteError(ErrorCategory.InvalidOperation, fastPackageReference, ex.Message);
            } finally {
                // Change back to user specified security protocol
                System.Net.ServicePointManager.SecurityProtocol = securityProtocol;
            }
        }
示例#9
0
        /// <summary>
        /// </summary>
        /// <param name="fastPackageReference"></param>
        /// <param name="request">
        ///     An object passed in from the CORE that contains functions that can be used to interact with the
        ///     CORE and HOST
        /// </param>
        public void InstallPackage(string fastPackageReference, NuGetRequest request)
        {
            // Nice-to-have put a debug message in that tells what's going on.
            request.Debug("Calling '{0}::InstallPackage' '{1}'", PackageProviderName, fastPackageReference);

            var pkgRef = request.GetPackageByFastpath(fastPackageReference);

            if (pkgRef == null)
            {
                request.Error(ErrorCategory.InvalidArgument, fastPackageReference, Constants.Messages.UnableToResolvePackage);
                return;
            }

            // need to make sure that the original package's sources list is tried first.
            request.OriginalSources = pkgRef.Sources;

            var dependencies = request.GetUninstalledPackageDependencies(pkgRef).Reverse().ToArray();
            int progressId   = 0;

            if (dependencies.Length > 0)
            {
                progressId = request.StartProgress(0, "Installing package '{0}'", pkgRef.GetCanonicalId(request));
            }
            var n = 0;

            foreach (var d in dependencies)
            {
                request.Progress(progressId, (n * 100 / (dependencies.Length + 1)) + 1, "Installing dependent package '{0}'", d.GetCanonicalId(request));
                if (!request.InstallSinglePackage(d))
                {
                    request.Error(ErrorCategory.InvalidResult, pkgRef.GetCanonicalId(request), Constants.Messages.DependentPackageFailedInstall, d.GetCanonicalId(request));
                    return;
                }
                n++;
                request.Progress(progressId, (n * 100 / (dependencies.Length + 1)), "Installed dependent package '{0}'", d.GetCanonicalId(request));
            }

            // got this far, let's install the package we came here for.
            if (!request.InstallSinglePackage(pkgRef))
            {
                // package itself didn't install.
                // roll that back out everything we did install.
                // and get out of here.
                request.Error(ErrorCategory.InvalidResult, pkgRef.GetCanonicalId(request), Constants.Messages.PackageFailedInstall, pkgRef.GetCanonicalId(request));
                request.CompleteProgress(progressId, false);
            }
            request.CompleteProgress(progressId, true);
        }
        /// <summary>
        /// Finds packages given a locally-accessible filename
        ///
        /// Package information must be returned using <c>request.YieldPackage(...)</c> function.
        /// </summary>
        /// <param name="file">the full path to the file to determine if it is a package</param>
        /// <param name="id">if this is greater than zero (and the number should have been generated using <c>StartFind(...)</c>, the core is calling this multiple times to do a batch search request. The operation can be delayed until <c>CompleteFind(...)</c> is called</param>
        /// <param name="request">An object passed in from the PackageManagement that contains functions that can be used to interact with its Provider</param>
        public void FindPackageByFile(string file, int id, NuGetRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            request.Debug(Resources.Messages.DebugInfoCallMethod3, PackageProviderName, file, id);

            var pkgItem = request.GetPackageByFilePath(Path.GetFullPath(file));

            if (pkgItem != null)
            {
                request.YieldPackage(pkgItem, file);
            }
        }
示例#11
0
        /// <summary>
        /// Search the entire repository for the case when a user does not provider package name or uses wildcards in the name.
        /// </summary>
        /// <param name="searchTerm"></param>
        /// <param name="nugetRequest"></param>
        /// <returns></returns>
        public IEnumerable <IPackage> Search(string searchTerm, NuGetRequest nugetRequest)
        {
            if (nugetRequest == null)
            {
                yield break;
            }

            nugetRequest.Debug(Messages.DebugInfoCallMethod3, "HttpClientPackageRepository", "Search", searchTerm);

            var searchQuery = searchTerm.MakeSearchQuery(_queryUri, nugetRequest.AllowPrereleaseVersions.Value, nugetRequest.AllVersions.Value);

            foreach (var pkg in SendRequest(searchQuery, nugetRequest))
            {
                yield return(pkg);
            }
        }
示例#12
0
        /// <summary>
        ///     Removes/Unregisters a package source
        /// </summary>
        /// <param name="name">The name or location of a package source to remove.</param>
        /// <param name="request">
        ///     An object passed in from the CORE that contains functions that can be used to interact with the
        ///     CORE and HOST
        /// </param>
        public void RemovePackageSource(string name, NuGetRequest request)
        {
            // Nice-to-have put a debug message in that tells what's going on.
            request.Debug("Calling '{0}::RemovePackageSource' '{1}'", PackageProviderName, name);

            var src = request.FindRegisteredSource(name);

            if (src == null)
            {
                request.Warning(Constants.Messages.UnableToResolveSource, name);
                return;
            }

            request.RemovePackageSource(src.Name);
            request.YieldPackageSource(src.Name, src.Location, src.Trusted, false, src.IsValidated);
        }
示例#13
0
        /// <summary>
        /// Search the entire repository for the case when a user does not provider package name or uses wildcards in the name.
        /// </summary>
        /// <param name="searchTerm">The Searchterm</param>
        /// <param name="nugetRequest"></param>
        /// <returns></returns>
        public IEnumerable <IPackage> Search(string searchTerm, NuGetRequest nugetRequest)
        {
            var packages = SearchImpl(searchTerm, nugetRequest);

            if (packages == null)
            {
                return(Enumerable.Empty <IPackage>());
            }

            if (nugetRequest != null && nugetRequest.AllVersions.Value)
            {
                //return whatever we can find
                return(packages);
            }

            //return the lastest version
            return(packages.GroupBy(p => p.Id).Select(each => each.OrderByDescending(pp => pp.Version).FirstOrDefault()));
        }
        /// <summary>
        /// Search the entire repository for the case when a user does not provider package name or uses wildcards in the name.
        /// </summary>
        /// <param name="searchTerm">The Searchterm</param>
        /// <param name="nugetRequest"></param>
        /// <returns></returns>
        public NuGetSearchResult Search(NuGetSearchContext searchContext, NuGetRequest nugetRequest)
        {
            var packages = SearchImpl(this.ResourceProvider.GetSearchQueryDelegate(searchContext.SearchTerms), nugetRequest);

            if (packages == null)
            {
                return(searchContext.MakeResult(Enumerable.Empty <IPackage>()));
            }

            if (nugetRequest != null && nugetRequest.AllVersions.Value)
            {
                //return whatever we can find
                return(searchContext.MakeResult(packages));
            }

            //return the latest version
            return(searchContext.MakeResult(packages.GroupBy(p => p.Id).Select(each => each.OrderByDescending(pp => pp.Version).FirstOrDefault())));
        }
示例#15
0
        /// <summary>
        /// Find-Package
        /// </summary>
        /// <param name="packageId">package Id</param>
        /// <param name="version">package version</param>
        /// <param name="request"></param>
        /// <returns></returns>
        public IPackage FindPackage(string packageId, SemanticVersion version, NuGetRequest request)
        {
            if (string.IsNullOrWhiteSpace(packageId))
            {
                return(null);
            }

            request.Debug(Messages.DebugInfoCallMethod3, "HttpClientPackageRepository", "FindPackage", packageId);

            var query = packageId.MakeFindPackageByIdQuery(_nugetFindPackageIdQueryFormat);

            var packages = NuGetClient.FindPackage(query, request);

            //Usually versions has a limited number, ToArray should be ok.
            var versions = version.GetComparableVersionStrings().ToArray();

            //Will only enumerate packages once
            return(packages.FirstOrDefault(package => packageId.Equals(package.Id, StringComparison.OrdinalIgnoreCase) && versions.Contains(package.Version, StringComparer.OrdinalIgnoreCase)));
        }
        /// <summary>
        /// Removes/Unregisters a package source
        /// </summary>
        /// <param name="name">The name or location of a package source to remove.</param>
        /// <param name="request">An object passed in from the PackageManagement that contains functions that can be used to interact with its Provider</param>
        public void RemovePackageSource(string name, NuGetRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            request.Debug(Resources.Messages.DebugInfoCallMethod, PackageProviderName, "RemovePackageSource");

            var src = request.FindRegisteredSource(name);

            if (src == null)
            {
                request.Warning(Constants.Messages.UnableToResolveSource, name);
                return;
            }

            request.RemovePackageSource(src.Name);
            request.YieldPackageSource(src.Name, src.Location, src.Trusted, false, src.IsValidated);
        }
示例#17
0
        /// <summary>
        ///     Downloads a remote package file to a local location.
        /// </summary>
        /// <param name="fastPackageReference"></param>
        /// <param name="location"></param>
        /// <param name="request">
        ///     An object passed in from the CORE that contains functions that can be used to interact with the
        ///     CORE and HOST
        /// </param>
        /// <returns></returns>
        public void DownloadPackage(string fastPackageReference, string location, NuGetRequest request)
        {
            // Nice-to-have put a debug message in that tells what's going on.
            request.Debug("Calling '{0}::DownloadPackage' '{1}','{2}'", PackageProviderName, fastPackageReference, location);

            var pkgRef = request.GetPackageByFastpath(fastPackageReference);

            if (pkgRef == null)
            {
                request.Error(ErrorCategory.InvalidArgument, fastPackageReference, Constants.Messages.UnableToResolvePackage);
                return;
            }

            // cheap and easy copy to location.
            using (var input = pkgRef.Package.GetStream()) {
                using (var output = new FileStream(location, FileMode.Create, FileAccess.Write, FileShare.Read)) {
                    input.CopyTo(output);
                }
            }
        }
        /// <summary>
        /// Installs a given package.
        /// </summary>
        /// <param name="fastPackageReference">A provider supplied identifier that specifies an exact package</param>
        /// <param name="request">An object passed in from the PackageManagement that contains functions that can be used to interact with its Provider</param>
        public void InstallPackage(string fastPackageReference, NuGetRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            request.Debug(Resources.Messages.DebugInfoCallMethod3, PackageProviderName, "InstallPackage", fastPackageReference);

            try {
                var pkgItem = request.GetPackageByFastpath(fastPackageReference);
                if (pkgItem == null)
                {
                    request.WriteError(ErrorCategory.InvalidArgument, fastPackageReference, Constants.Messages.UnableToResolvePackage);
                    return;
                }

                if ((pkgItem.PackageSource == null) || (pkgItem.PackageSource.Location == null) || (pkgItem.Package == null))
                {
                    request.Debug(Resources.Messages.VariableCheck, "PackageSource or PackageSource.Location or Package object", "null");
                    request.WriteError(ErrorCategory.ObjectNotFound, fastPackageReference, Constants.Messages.UnableToResolvePackage, pkgItem.Id);
                    return;
                }

                request.Debug(Resources.Messages.VariableCheck, "Package version", pkgItem.Version);
                request.Debug(Resources.Messages.VariableCheck, "Request's Destination", request.Destination);

                // got this far, let's install the package we came here for.
                if (!NuGetClient.InstallOrDownloadPackageHelper(pkgItem, request, Constants.Install,
                                                                (packageItem, progressTracker) => NuGetClient.InstallSinglePackage(packageItem, request, progressTracker)))
                {
                    // package itself didn't install. Write error
                    request.WriteError(ErrorCategory.InvalidResult, pkgItem.Id, Constants.Messages.PackageFailedInstallOrDownload, pkgItem.Id, CultureInfo.CurrentCulture.TextInfo.ToLower(Constants.Install));

                    return;
                }
            } catch (Exception ex) {
                ex.Dump(request);
                request.WriteError(ErrorCategory.InvalidOperation, fastPackageReference, ex.Message);
            }
        }
示例#19
0
        public virtual IPackageRepository CreateRepository(string packageSource, NuGetRequest request)
        {
            if (packageSource == null)
            {
                throw new ArgumentNullException("packageSource");
            }

            // we cannot call new uri on file path on linux because it will error out
            if (System.IO.Directory.Exists(packageSource))
            {
                return(new LocalPackageRepository(packageSource, request));
            }

            Uri uri = new Uri(packageSource);

            if (uri.IsFile)
            {
                return(new LocalPackageRepository(uri.LocalPath, request));
            }

            return(new HttpClientPackageRepository(packageSource, request));
        }
        /// <summary>
        /// Downloads a remote package file to a local location.
        /// </summary>
        /// <param name="fastPackageReference"></param>
        /// <param name="destLocation"></param>
        /// <param name="request">An object passed in from the PackageManagement that contains functions that can be used to interact with its Provider</param>
        public void DownloadPackage(string fastPackageReference, string destLocation, NuGetRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            request.Debug(Resources.Messages.DebugInfoCallMethod3, PackageProviderName, fastPackageReference, destLocation);

            try {
                var pkgItem = request.GetPackageByFastpath(fastPackageReference);
                if (pkgItem == null)
                {
                    request.WriteError(ErrorCategory.InvalidArgument, fastPackageReference, Constants.Messages.UnableToResolvePackage);
                    return;
                }

                pkgItem.PackageSource.Repository.DownloadPackage(new PublicObjectView(pkgItem), destLocation, request);
            } catch (Exception ex) {
                ex.Dump(request);
                request.WriteError(ErrorCategory.InvalidOperation, fastPackageReference, ex.Message);
            }
        }
        /// <summary>
        /// Downloads a remote package file to a local location.
        /// </summary>
        /// <param name="fastPackageReference"></param>
        /// <param name="destLocation"></param>
        /// <param name="request">An object passed in from the PackageManagement that contains functions that can be used to interact with its Provider</param>
        public void DownloadPackage(string fastPackageReference, string destLocation, NuGetRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            request.Debug(Resources.Messages.DebugInfoCallMethod3, PackageProviderName, fastPackageReference, destLocation);

            try {
                var pkgItem = request.GetPackageByFastpath(fastPackageReference);
                if (pkgItem == null)
                {
                    request.WriteError(ErrorCategory.InvalidArgument, fastPackageReference, Constants.Messages.UnableToResolvePackage);
                    return;
                }

                NuGetClient.InstallOrDownloadPackageHelper(pkgItem, request, Constants.Download,
                                                           (packageItem, progressTracker) => NuGetClient.DownloadSinglePackage(packageItem, request, destLocation, progressTracker));
            } catch (Exception ex) {
                ex.Dump(request);
                request.WriteError(ErrorCategory.InvalidOperation, fastPackageReference, ex.Message);
            }
        }
示例#22
0
 internal string GetCanonicalId(NuGetRequest request)
 {
     return _canonicalId ?? (_canonicalId = request.ProviderServices.GetCanonicalPackageId(request.PackageProviderName, Id, Version, PackageSource == null ? null : PackageSource.Location));
 }
        /// <summary>
        /// Searches package sources given name and version information
        ///
        /// Package information must be returned using <c>request.YieldPackage(...)</c> function.
        /// </summary>
        /// <param name="name">a name or partial name of the package(s) requested</param>
        /// <param name="requiredVersion">A specific version of the package. Null or empty if the user did not specify</param>
        /// <param name="minimumVersion">A minimum version of the package. Null or empty if the user did not specify</param>
        /// <param name="maximumVersion">A maximum version of the package. Null or empty if the user did not specify</param>
        /// <param name="id">if this is greater than zero (and the number should have been generated using <c>StartFind(...)</c>, the core is calling this multiple times to do a batch search request. The operation can be delayed until <c>CompleteFind(...)</c> is called</param>
        /// <param name="request">An object passed in from the PackageManagement that contains functions that can be used to interact with its Provider</param>
        public void FindPackage(string name, string requiredVersion, string minimumVersion, string maximumVersion, int id, NuGetRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            // true if we want to include the max and min version
            bool minInclusive = true;
            bool maxInclusive = true;

            // If finding by canonical id, then the version follows dependency version requirement
            if (request.GetOptionValue("FindByCanonicalId").IsTrue())
            {
                // Use the dependency version if no min and max is supplied
                if (String.IsNullOrWhiteSpace(maximumVersion) && String.IsNullOrWhiteSpace(minimumVersion))
                {
                    DependencyVersion depVers = DependencyVersion.ParseDependencyVersion(requiredVersion);
                    maximumVersion = depVers.MaxVersion.ToStringSafe();
                    minimumVersion = depVers.MinVersion.ToStringSafe();
                    minInclusive   = depVers.IsMinInclusive;
                    maxInclusive   = depVers.IsMaxInclusive;

                    // set required version if we have both min max as the same value.
                    if (depVers.MaxVersion != null && depVers.MinVersion != null &&
                        depVers.MaxVersion == depVers.MinVersion && minInclusive && maxInclusive)
                    {
                        requiredVersion = maximumVersion;
                    }
                    else
                    {
                        requiredVersion = null;
                    }
                }
            }

            request.Debug(Resources.Messages.DebugInfoCallMethod, PackageProviderName, string.Format(CultureInfo.InvariantCulture, "FindPackage' - name='{0}', requiredVersion='{1}',minimumVersion='{2}', maximumVersion='{3}'", name, requiredVersion, minimumVersion, maximumVersion));

            NormalizeVersion(request, ref requiredVersion, ref minimumVersion, ref maximumVersion);

            try {
                // If there are any packages, yield and return
                if (request.YieldPackages(request.GetPackageById(name, request, requiredVersion, minimumVersion, maximumVersion, minInclusive, maxInclusive), name))
                {
                    return;
                }

                // Check if the name contains wildcards. If not, return. This matches the behavior as "Get-module xje"
                if (!String.IsNullOrWhiteSpace(name) && !WildcardPattern.ContainsWildcardCharacters(name))
                {
                    return;
                }

                // In the case of the package name is null or contains wildcards, error out if a user puts version info
                if (!String.IsNullOrWhiteSpace(requiredVersion) || !String.IsNullOrWhiteSpace(minimumVersion) || !String.IsNullOrWhiteSpace(maximumVersion))
                {
                    request.Warning(Constants.Messages.MissingRequiredParameter, "name");
                    return;
                }



                // Have we been cancelled?
                if (request.IsCanceled)
                {
                    request.Debug(Resources.Messages.RequestCanceled, PackageProviderName, "FindPackage");

                    return;
                }

                // A user does not provide the package full Name at all Or used wildcard in the name. Let's try searching the entire repository for matches.
                request.YieldPackages(request.SearchForPackages(name), name);
            }
            catch (Exception ex)
            {
                ex.Dump(request);
            }
        }
示例#24
0
 internal string GetCanonicalId(NuGetRequest request)
 {
     return(_canonicalId ?? (_canonicalId = request.ProviderServices.GetCanonicalPackageId(request.PackageProviderName, Id, Version, PackageSource == null ? null : PackageSource.Location)));
 }
        /// <summary>
        /// This is called when the user is adding (or updating) a package source
        ///
        /// If this PROVIDER doesn't support user-defined package sources, remove this method.
        /// </summary>
        /// <param name="name">The name of the package source. If this parameter is null or empty the PROVIDER should use the location as the name (if the PROVIDER actually stores names of package sources)</param>
        /// <param name="location">The location (ie, directory, URL, etc) of the package source. If this is null or empty, the PROVIDER should use the name as the location (if valid)</param>
        /// <param name="trusted">A boolean indicating that the user trusts this package source. Packages returned from this source should be marked as 'trusted'</param>
        /// <param name="request">An object passed in from the PackageManagement that contains functions that can be used to interact with its Provider</param>
        public void AddPackageSource(string name, string location, bool trusted, NuGetRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            try {
                request.Debug(string.Format(CultureInfo.InvariantCulture, "AddPackageSource - ProviderName = '{0}', name='{1}', location='{2}', trusted='{3}'", PackageProviderName, name, location, trusted));

                // Error out if a user does not provide package source Name
                if (string.IsNullOrWhiteSpace(name))
                {
                    request.WriteError(ErrorCategory.InvalidArgument, Constants.Parameters.Name, Constants.Messages.MissingRequiredParameter, Constants.Parameters.Name);
                    return;
                }

                if (string.IsNullOrWhiteSpace(location))
                {
                    request.WriteError(ErrorCategory.InvalidArgument, Constants.Parameters.Location, Constants.Messages.MissingRequiredParameter, Constants.Parameters.Location);
                    return;
                }

                request.Debug(Resources.Messages.DebugInfoCallMethod, PackageProviderName, "GetOptionValue");
                // if this is supposed to be an update, there will be a dynamic parameter set for IsUpdatePackageSource
                var isUpdate = request.GetOptionValue(Constants.Parameters.IsUpdate).IsTrue();

                request.Debug(Resources.Messages.VariableCheck, "IsUpdate", isUpdate);

                // if your source supports credentials you get get them too:
                // string username =request.Username;
                // SecureString password = request.Password;
                // feel free to send back an error here if your provider requires credentials for package sources.

                // check first that we're not clobbering an existing source, unless this is an update

                request.Debug(Resources.Messages.DebugInfoCallMethod, PackageProviderName, string.Format(CultureInfo.InvariantCulture, "FindRegisteredSource -name'{0}'", name));

                var src = request.FindRegisteredSource(name);

                if (src != null && !isUpdate)
                {
                    // tell the user that there's one here already
                    request.WriteError(ErrorCategory.InvalidArgument, name, Constants.Messages.PackageSourceExists, name);
                    return;
                }

                // conversely, if it didn't find one, and it is an update, that's bad too:
                if (src == null && isUpdate)
                {
                    // you can't find that package source? Tell that to the user
                    request.WriteError(ErrorCategory.ObjectNotFound, name, Constants.Messages.UnableToResolveSource, name);
                    return;
                }

                // ok, we know that we're ok to save this source
                // next we check if the location is valid (if we support that kind of thing)

                var validated = false;

                if (!request.SkipValidate.Value)
                {
                    // the user has not opted to skip validating the package source location, so check if the source is valid
                    validated = request.ValidateSourceLocation(location);

                    if (!validated)
                    {
                        request.WriteError(ErrorCategory.InvalidData, name, Constants.Messages.SourceLocationNotValid, location);
                        return;
                    }

                    request.Verbose(Resources.Messages.SuccessfullyValidated, name);
                }

                // it's good to check just before you actually write something to see if the user has cancelled the operation
                if (request.IsCanceled)
                {
                    return;
                }

                // looking good -- store the package source.
                request.AddPackageSource(name, location, trusted, validated);

                // Yield the package source back to the caller.
                request.YieldPackageSource(name, location, trusted, true /*since we just registered it*/, validated);
            }
            catch (Exception e)
            {
                e.Dump(request);
            }
        }
示例#26
0
 /// <summary>
 ///     Returns a collection of strings to the client advertizing features this provider supports.
 /// </summary>
 /// <param name="request">
 ///     An object passed in from the CORE that contains functions that can be used to interact with the
 ///     CORE and HOST
 /// </param>
 public void GetFeatures(NuGetRequest request)
 {
     // Nice-to-have put a debug message in that tells what's going on.
     request.Debug("Calling '{0}::GetFeatures' ", PackageProviderName);
     request.Yield(Features);
 }
示例#27
0
        /// <summary>
        ///     Returns the packages that are installed
        /// </summary>
        /// <param name="name">the package name to match. Empty or null means match everything</param>
        /// <param name="requiredVersion">
        ///     the specific version asked for. If this parameter is specified (ie, not null or empty
        ///     string) then the minimum and maximum values are ignored
        /// </param>
        /// <param name="minimumVersion">
        ///     the minimum version of packages to return . If the <code>requiredVersion</code> parameter
        ///     is specified (ie, not null or empty string) this should be ignored
        /// </param>
        /// <param name="maximumVersion">
        ///     the maximum version of packages to return . If the <code>requiredVersion</code> parameter
        ///     is specified (ie, not null or empty string) this should be ignored
        /// </param>
        /// <param name="request">
        ///     An object passed in from the CORE that contains functions that can be used to interact with
        ///     the CORE and HOST
        /// </param>
        public void GetInstalledPackages(string name, string requiredVersion, string minimumVersion, string maximumVersion, NuGetRequest request)
        {
            // Nice-to-have put a debug message in that tells what's going on.
            request.Debug("Calling '{0}::GetInstalledPackages' '{1}','{2}','{3}','{4}'", PackageProviderName, name, requiredVersion, minimumVersion, maximumVersion);

            if (requiredVersion != null)
            {
                minimumVersion = null;
                maximumVersion = null;
            }
            else
            {
                minimumVersion = minimumVersion.FixVersion();
                maximumVersion = maximumVersion.FixVersion();
            }

            if (!IsValidVersionRange(minimumVersion, maximumVersion))
            {
                request.Error(ErrorCategory.InvalidArgument, minimumVersion + maximumVersion, Constants.Messages.InvalidVersionRange, minimumVersion, maximumVersion);
                return;
            }

            // look in the destination directory for directories that contain nupkg files.
            var subdirs = Directory.EnumerateDirectories(request.Destination);

            foreach (var subdir in subdirs)
            {
                var nupkgs = Directory.EnumerateFileSystemEntries(subdir, "*.nupkg", SearchOption.TopDirectoryOnly);

                foreach (var pkgFile in nupkgs)
                {
                    var pkgItem = request.GetPackageByFilePath(pkgFile);

                    if (pkgItem != null && pkgItem.IsInstalled)
                    {
                        if (pkgItem.Id.Equals(name, StringComparison.CurrentCultureIgnoreCase))
                        {
                            if (!string.IsNullOrWhiteSpace(requiredVersion))
                            {
                                if (pkgItem.Package.Version != new SemanticVersion(requiredVersion))
                                {
                                    continue;
                                }
                            }
                            else
                            {
                                if (!string.IsNullOrWhiteSpace(minimumVersion) && pkgItem.Package.Version < new SemanticVersion(minimumVersion))
                                {
                                    continue;
                                }
                                if (!string.IsNullOrWhiteSpace(maximumVersion) && pkgItem.Package.Version < new SemanticVersion(maximumVersion))
                                {
                                    continue;
                                }
                            }
                            request.YieldPackage(pkgItem, name);
                            break;
                        }
                        if (string.IsNullOrEmpty(name) || pkgItem.Id.IndexOf(name, StringComparison.CurrentCultureIgnoreCase) > -1)
                        {
                            if (!request.YieldPackage(pkgItem, name))
                            {
                                return;
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Searches package sources given name and version information
        ///
        /// Package information must be returned using <c>request.YieldPackage(...)</c> function.
        /// </summary>
        /// <param name="name">a name or partial name of the package(s) requested</param>
        /// <param name="requiredVersion">A specific version of the package. Null or empty if the user did not specify</param>
        /// <param name="minimumVersion">A minimum version of the package. Null or empty if the user did not specify</param>
        /// <param name="maximumVersion">A maximum version of the package. Null or empty if the user did not specify</param>
        /// <param name="id">if this is greater than zero (and the number should have been generated using <c>StartFind(...)</c>, the core is calling this multiple times to do a batch search request. The operation can be delayed until <c>CompleteFind(...)</c> is called</param>
        /// <param name="request">An object passed in from the PackageManagement that contains functions that can be used to interact with its Provider</param>
        public void FindPackage(string name, string requiredVersion, string minimumVersion, string maximumVersion, int id, NuGetRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            // true if we want to include the max and min version
            bool minInclusive = true;
            bool maxInclusive = true;

            // If finding by canonical id, then the version follows dependency version requirement
            if (request.GetOptionValue("FindByCanonicalId").IsTrue())
            {
                // Use the dependency version if no min and max is supplied
                if (String.IsNullOrWhiteSpace(maximumVersion) && String.IsNullOrWhiteSpace(minimumVersion))
                {
                    DependencyVersion depVers = DependencyVersion.ParseDependencyVersion(requiredVersion);
                    maximumVersion = depVers.MaxVersion.ToStringSafe();
                    minimumVersion = depVers.MinVersion.ToStringSafe();
                    minInclusive   = depVers.IsMinInclusive;
                    maxInclusive   = depVers.IsMaxInclusive;

                    // set required version if we have both min max as the same value.
                    if (depVers.MaxVersion != null && depVers.MinVersion != null &&
                        depVers.MaxVersion == depVers.MinVersion && minInclusive && maxInclusive)
                    {
                        requiredVersion = maximumVersion;
                    }
                    else
                    {
                        requiredVersion = null;
                    }
                }
            }

            request.Debug(Resources.Messages.DebugInfoCallMethod, PackageProviderName, string.Format(CultureInfo.InvariantCulture, "FindPackage' - name='{0}', requiredVersion='{1}',minimumVersion='{2}', maximumVersion='{3}'", name, requiredVersion, minimumVersion, maximumVersion));

            NormalizeVersion(request, ref requiredVersion, ref minimumVersion, ref maximumVersion);

            // First call to SearchPackages will just look for the packages with current credentials
            if (SearchPackages(name, requiredVersion, minimumVersion, maximumVersion, minInclusive, maxInclusive, id, request))
            {
                return;
            }

            if (request.CredentialUsername.IsNullOrEmpty())
            {
                // If no packages were found, try again using credentials retrieved from credential provider
                // First call to the credential provider is to get credentials, but if those credentials fail,
                // we call the cred provider again to ask the user for new credentials, and then search pkgs again using new creds
                var query       = new Uri(request.FindRegisteredSource(request.Sources.First()).Location.IsNullOrEmpty() ? request.Sources.First() : request.FindRegisteredSource(request.Sources.First()).Location);
                var credentials = request.GetCredsFromCredProvider(query.AbsoluteUri, request, false);
                var newclient   = PathUtility.GetHttpClientHelper(credentials.UserName, credentials.SecurePassword, request.WebProxy);
                request.SetHttpClient(newclient);

                if (SearchPackages(name, requiredVersion, minimumVersion, maximumVersion, minInclusive, maxInclusive, id, request))
                {
                    return;
                }

                // Calling the credential provider for a second time, using -IsRetry
                credentials = request.GetCredsFromCredProvider(query.AbsoluteUri, request, true);
                newclient   = PathUtility.GetHttpClientHelper(credentials.UserName, credentials.SecurePassword, request.WebProxy);
                request.SetHttpClient(newclient);

                if (SearchPackages(name, requiredVersion, minimumVersion, maximumVersion, minInclusive, maxInclusive, id, request))
                {
                    return;
                }
            }
        }
        public bool SearchPackages(string name, string requiredVersion, string minimumVersion, string maximumVersion, bool minInclusive, bool maxInclusive, int id, NuGetRequest request)
        {
            try {
                // If there are any packages, yield and return
                if (request.YieldPackages(request.GetPackageById(name, request, requiredVersion, minimumVersion, maximumVersion, minInclusive, maxInclusive), name))
                {
                    return(true);
                }

                // Check if the name contains wildcards. If not, return. This matches the behavior as "Get-module xje"
                if (!String.IsNullOrWhiteSpace(name) && !WildcardPattern.ContainsWildcardCharacters(name))
                {
                    return(false);
                }

                // In the case of the package name is null or contains wildcards, error out if a user puts version info
                if (!String.IsNullOrWhiteSpace(requiredVersion) || !String.IsNullOrWhiteSpace(minimumVersion) || !String.IsNullOrWhiteSpace(maximumVersion))
                {
                    request.Warning(Constants.Messages.MissingRequiredParameter, "name");
                    return(false);
                }



                // Have we been cancelled?
                if (request.IsCanceled)
                {
                    request.Debug(Resources.Messages.RequestCanceled, PackageProviderName, "FindPackage");

                    return(false);
                }

                // A user does not provide the package full Name at all Or used wildcard in the name. Let's try searching the entire repository for matches.
                if (request.YieldPackages(request.SearchForPackages(name), name))
                {
                    return(true);
                }
            }
            catch (Exception ex)
            {
                ex.Dump(request);
            }

            return(false);
        }
示例#30
0
        /// <summary>
        /// </summary>
        /// <param name="name"></param>
        /// <param name="requiredVersion"></param>
        /// <param name="minimumVersion"></param>
        /// <param name="maximumVersion"></param>
        /// <param name="id"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        public void FindPackage(string name, string requiredVersion, string minimumVersion, string maximumVersion, int id, NuGetRequest request)
        {
            // Nice-to-have put a debug message in that tells what's going on.
            request.Debug("Calling '{0}::FindPackage' '{1}','{2}','{3}','{4}','{5}'", PackageProviderName, name, requiredVersion, minimumVersion, maximumVersion, id);

            requiredVersion = requiredVersion.FixVersion();
            if (!string.IsNullOrEmpty(requiredVersion))
            {
                if (request.FindByCanonicalId && requiredVersion.IndexOfAny("()[],".ToCharArray()) == -1)
                {
                    // when resolving packages via a canonical id, treat a lone version (ie  1.0  ->  1.0 <= x) string as a nuget version range:
                    minimumVersion  = requiredVersion;
                    maximumVersion  = null;
                    requiredVersion = null;
                }
                else
                {
                    minimumVersion = null;
                    maximumVersion = null;
                }
            }
            else
            {
                minimumVersion = minimumVersion.FixVersion();
                maximumVersion = maximumVersion.FixVersion();
            }

            if (!IsValidVersionRange(minimumVersion, maximumVersion))
            {
                request.Error(ErrorCategory.InvalidArgument, minimumVersion + maximumVersion, Constants.Messages.InvalidVersionRange, minimumVersion, maximumVersion);
                return;
            }
            // get the package by ID first.
            // if there are any packages, yield and return
            if (!string.IsNullOrWhiteSpace(name))
            {
                if (request.YieldPackages(request.GetPackageById(name, requiredVersion, minimumVersion, maximumVersion), name) || request.FoundPackageById)
                {
                    // if we actaully found some by that id, but didn't make it past the filter, we're done.
                    return;
                }
            }
            // have we been cancelled?
            if (request.IsCanceled)
            {
                return;
            }

            // Try searching for matches and returning those.
            request.YieldPackages(request.SearchForPackages(name, requiredVersion, minimumVersion, maximumVersion), name);
            request.Debug("Finished '{0}::FindPackage' '{1}','{2}','{3}','{4}','{5}'", PackageProviderName, name, requiredVersion, minimumVersion, maximumVersion, id);
        }
        /// <summary>
        /// Returns the packages that are installed. This method is called when a user type get-package, install-package and uninstall-package.
        /// </summary>
        /// <param name="name">the package name to match. Empty or null means match everything</param>
        /// <param name="requiredVersion">the specific version asked for. If this parameter is specified (ie, not null or empty string) then the minimum and maximum values are ignored</param>
        /// <param name="minimumVersion">the minimum version of packages to return . If the <code>requiredVersion</code> parameter is specified (ie, not null or empty string) this should be ignored</param>
        /// <param name="maximumVersion">the maximum version of packages to return . If the <code>requiredVersion</code> parameter is specified (ie, not null or empty string) this should be ignored</param>
        /// <param name="request">An object passed in from the PackageManagement that contains functions that can be used to interact with its Provider</param>
        public void GetInstalledPackages(string name, string requiredVersion, string minimumVersion, string maximumVersion, NuGetRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            request.Debug(Resources.Messages.DebugInfoCallMethod, PackageProviderName, string.Format(CultureInfo.InvariantCulture, "GetInstalledPackages' - name='{0}', requiredVersion='{1}',minimumVersion='{2}', maximumVersion='{3}'", name, requiredVersion, minimumVersion, maximumVersion));

            // In the case of the package name is null or contains wildcards, error out if a user puts version info
            if (!String.IsNullOrWhiteSpace(requiredVersion) || !String.IsNullOrWhiteSpace(minimumVersion) || !String.IsNullOrWhiteSpace(maximumVersion))
            {
                // A user provides the version info but missing name
                if (string.IsNullOrWhiteSpace(name))
                {
                    request.Warning(Constants.Messages.MissingRequiredParameter, "name");
                    return;
                }

                // A user provides the version info but the name containing wildcards
                if (WildcardPattern.ContainsWildcardCharacters(name))
                {
                    return;
                }
            }

            NormalizeVersion(request, ref requiredVersion, ref minimumVersion, ref maximumVersion);

            request.GetInstalledPackages(name, requiredVersion, minimumVersion, maximumVersion);
        }
示例#32
0
        /// <summary>
        ///     This is called when the user is adding (or updating) a package source
        ///     If this PROVIDER doesn't support user-defined package sources, remove this method.
        /// </summary>
        /// <param name="name">
        ///     The name of the package source. If this parameter is null or empty the PROVIDER should use the
        ///     location as the name (if the PROVIDER actually stores names of package sources)
        /// </param>
        /// <param name="location">
        ///     The location (ie, directory, URL, etc) of the package source. If this is null or empty, the
        ///     PROVIDER should use the name as the location (if valid)
        /// </param>
        /// <param name="trusted">
        ///     A boolean indicating that the user trusts this package source. Packages returned from this source
        ///     should be marked as 'trusted'
        /// </param>
        /// <param name="request">
        ///     An object passed in from the CORE that contains functions that can be used to interact with the
        ///     CORE and HOST
        /// </param>
        public void AddPackageSource(string name, string location, bool trusted, NuGetRequest request)
        {
            // Nice-to-have put a debug message in that tells what's going on.
            request.Debug("Calling '{0}::AddPackageSource' '{1}','{2}','{3}'", PackageProviderName, name, location, trusted);

            // if they didn't pass in a name, use the location as a name. (if you support that kind of thing)
            name = string.IsNullOrEmpty(name) ? location : name;

            // let's make sure that they've given us everything we need.
            if (string.IsNullOrEmpty(name))
            {
                request.Error(ErrorCategory.InvalidArgument, Constants.Parameters.Name, Constants.Messages.MissingRequiredParameter, Constants.Parameters.Name);
                // we're done here.
                return;
            }

            if (string.IsNullOrEmpty(location))
            {
                request.Error(ErrorCategory.InvalidArgument, Constants.Parameters.Location, Constants.Messages.MissingRequiredParameter, Constants.Parameters.Location);
                // we're done here.
                return;
            }

            // if this is supposed to be an update, there will be a dynamic parameter set for IsUpdatePackageSource
            var isUpdate = request.GetOptionValue(Constants.Parameters.IsUpdate).IsTrue();

            // if your source supports credentials you get get them too:
            // string username =request.Username;
            // SecureString password = request.Password;
            // feel free to send back an error here if your provider requires credentials for package sources.

            // check first that we're not clobbering an existing source, unless this is an update

            var src = request.FindRegisteredSource(name);

            if (src != null && !isUpdate)
            {
                // tell the user that there's one here already
                request.Error(ErrorCategory.InvalidArgument, name ?? location, Constants.Messages.PackageSourceExists, name ?? location);
                // we're done here.
                return;
            }

            // conversely, if it didn't find one, and it is an update, that's bad too:
            if (src == null && isUpdate)
            {
                // you can't find that package source? Tell that to the user
                request.Error(ErrorCategory.ObjectNotFound, name ?? location, Constants.Messages.UnableToResolveSource, name ?? location);
                // we're done here.
                return;
            }

            // ok, we know that we're ok to save this source
            // next we check if the location is valid (if we support that kind of thing)

            var validated = false;

            if (!request.SkipValidate)
            {
                // the user has not opted to skip validating the package source location, so check that it's valid (talk to the url, or check if it's a valid directory, etc)
                // todo: insert code to check if the source is valid

                validated = request.ValidateSourceLocation(location);

                if (!validated)
                {
                    request.Error(ErrorCategory.InvalidData, name ?? location, Constants.Messages.SourceLocationNotValid, location);
                    // we're done here.
                    return;
                }

                // we passed validation!
            }

            // it's good to check just before you actaully write something to see if the user has cancelled the operation
            if (request.IsCanceled)
            {
                return;
            }

            // looking good -- store the package source
            // todo: create the package source (and store it whereever you store it)

            request.Verbose("Storing package source {0}", name);

            // actually yielded by the implementation.
            request.AddPackageSource(name, location, trusted, validated);

            // and, before you go, Yield the package source back to the caller.
            if (!request.YieldPackageSource(name, location, trusted, true /*since we just registered it*/, validated))
            {
                // always check the return value of a yield, since if it returns false, you don't keep returning data
                // this can happen if they have cancelled the operation.
                return;
            }
            // all done!
        }