protected override void ProcessRecord() { string nameArrayAsString = (Name == null || !Name.Any() || string.Equals(Name[0], "*") || Name[0] == null) ? "all" : string.Join(", ", Name); WriteDebug(String.Format("reading repository: {0}. Calling Read() API now", nameArrayAsString)); List <PSRepositoryInfo> items = RepositorySettings.Read(Name, out string[] errorList); // handle non-terminating errors foreach (string error in errorList) { WriteError(new ErrorRecord( new PSInvalidOperationException(error), "ErrorGettingSpecifiedRepo", ErrorCategory.InvalidOperation, this)); } foreach (PSRepositoryInfo repo in items) { WriteObject(repo); } }
public IEnumerable <CompletionResult> CompleteArgument( string commandName, string parameterName, string wordToComplete, CommandAst commandAst, IDictionary fakeBoundParameters) { List <PSRepositoryInfo> listOfRepositories = RepositorySettings.Read(null, out string[] _); wordToComplete = Utils.TrimQuotes(wordToComplete); var wordToCompletePattern = WildcardPattern.Get( pattern: string.IsNullOrWhiteSpace(wordToComplete) ? "*" : wordToComplete + "*", options: WildcardOptions.IgnoreCase); foreach (PSRepositoryInfo repo in listOfRepositories) { string repoName = repo.Name; if (wordToCompletePattern.IsMatch(repoName)) { yield return(new CompletionResult(Utils.QuoteName(repoName))); } } }
// This method calls iterates through repositories (by priority order) to search for the pkgs to install private List <PSResourceInfo> ProcessRepositories( string[] repository, bool trustRepository, PSCredential credential, bool skipDependencyCheck) { var listOfRepositories = RepositorySettings.Read(repository, out string[] _); var yesToAll = false; var noToAll = false; var findHelper = new FindHelper(_cancellationToken, _cmdletPassedIn); List <PSResourceInfo> allPkgsInstalled = new List <PSResourceInfo>(); foreach (var repo in listOfRepositories) { // If no more packages to install, then return if (!_pkgNamesToInstall.Any()) { return(allPkgsInstalled); } string repoName = repo.Name; _cmdletPassedIn.WriteVerbose(string.Format("Attempting to search for packages in '{0}'", repoName)); // Source is only trusted if it's set at the repository level to be trusted, -TrustRepository flag is true, -Force flag is true // OR the user issues trust interactively via console. var sourceTrusted = true; if (repo.Trusted == false && !trustRepository && !_force) { _cmdletPassedIn.WriteVerbose("Checking if untrusted repository should be used"); if (!(yesToAll || noToAll)) { // Prompt for installation of package from untrusted repository var message = string.Format(CultureInfo.InvariantCulture, MsgInstallUntrustedPackage, repoName); sourceTrusted = _cmdletPassedIn.ShouldContinue(message, MsgRepositoryNotTrusted, true, ref yesToAll, ref noToAll); } } if (!sourceTrusted && !yesToAll) { continue; } _cmdletPassedIn.WriteVerbose("Untrusted repository accepted as trusted source."); // If it can't find the pkg in one repository, it'll look for it in the next repo in the list var isLocalRepo = repo.Url.AbsoluteUri.StartsWith(Uri.UriSchemeFile + Uri.SchemeDelimiter, StringComparison.OrdinalIgnoreCase); // Finds parent packages and dependencies IEnumerable <PSResourceInfo> pkgsFromRepoToInstall = findHelper.FindByResourceName( name: _pkgNamesToInstall.ToArray(), type: ResourceType.None, version: _versionRange != null ? _versionRange.OriginalString : null, prerelease: _prerelease, tag: null, repository: new string[] { repoName }, credential: credential, includeDependencies: !skipDependencyCheck); if (!pkgsFromRepoToInstall.Any()) { _cmdletPassedIn.WriteVerbose(string.Format("None of the specified resources were found in the '{0}' repository.", repoName)); // Check in the next repository continue; } // Select the first package from each name group, which is guaranteed to be the latest version. // We should only have one version returned for each package name // e.g.: // PackageA (version 1.0) // PackageB (version 2.0) // PackageC (version 1.0) pkgsFromRepoToInstall = pkgsFromRepoToInstall.GroupBy( m => new { m.Name }).Select( group => group.First()).ToList(); // Check to see if the pkgs (including dependencies) are already installed (ie the pkg is installed and the version satisfies the version range provided via param) if (!_reinstall) { pkgsFromRepoToInstall = FilterByInstalledPkgs(pkgsFromRepoToInstall); } if (!pkgsFromRepoToInstall.Any()) { continue; } List <PSResourceInfo> pkgsInstalled = InstallPackage( pkgsFromRepoToInstall, repo.Url.AbsoluteUri, credential, isLocalRepo); foreach (PSResourceInfo pkg in pkgsInstalled) { _pkgNamesToInstall.RemoveAll(x => x.Equals(pkg.Name, StringComparison.InvariantCultureIgnoreCase)); } allPkgsInstalled.AddRange(pkgsInstalled); } // At this only package names left were those which could not be found in registered repositories foreach (string pkgName in _pkgNamesToInstall) { var message = String.Format("Package '{0}' with requested version range {1} could not be installed as it was not found in any registered repositories", pkgName, _versionRange.ToString()); var ex = new ArgumentException(message); var ResourceNotFoundError = new ErrorRecord(ex, "ResourceNotFoundError", ErrorCategory.ObjectNotFound, null); _cmdletPassedIn.WriteError(ResourceNotFoundError); } return(allPkgsInstalled); }
protected override void ProcessRecord() { string moduleManifestOrScriptPath; FileInfo moduleFileInfo; Hashtable parsedMetadataHash = new Hashtable(StringComparer.InvariantCultureIgnoreCase); // _path has been resolved, literal path does not need to be resolved _path = string.IsNullOrEmpty(_path) ? _literalPath : _path; // Returns the name of the file or the name of the directory, depending on path var pkgFileOrDir = new DirectoryInfo(_path); bool isScript = _path.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase); // TODO: think about including the repository the resource is being published to if (!ShouldProcess(string.Format("Publish resource '{0}' from the machine.", _path))) { WriteDebug("ShouldProcess is set to false."); return; } if (isScript) { // Get the .psd1 file or .ps1 file moduleManifestOrScriptPath = pkgFileOrDir.FullName; moduleFileInfo = new FileInfo(moduleManifestOrScriptPath); // Check that script metadata is valid // ParseScriptMetadata will write non-terminating error if it's unsucessful in parsing parsedMetadataHash = ParseScriptMetadata(moduleFileInfo); var message = string.Empty; // Check that the value is valid input // If it does not contain 'Version' or the Version empty or whitespace, write error if (!parsedMetadataHash.ContainsKey("Version") || String.IsNullOrWhiteSpace(parsedMetadataHash["Version"].ToString())) { message = "No version was provided in the script metadata. Script metadata must specify a version, author and description."; var ex = new ArgumentException(message); var InvalidScriptMetadata = new ErrorRecord(ex, "InvalidScriptMetadata", ErrorCategory.InvalidData, null); WriteError(InvalidScriptMetadata); return; } if (!parsedMetadataHash.ContainsKey("Author") || String.IsNullOrWhiteSpace(parsedMetadataHash["Author"].ToString())) { message = "No author was provided in the script metadata. Script metadata must specify a version, author and description."; var ex = new ArgumentException(message); var InvalidScriptMetadata = new ErrorRecord(ex, "InvalidScriptMetadata", ErrorCategory.InvalidData, null); WriteError(InvalidScriptMetadata); return; } if (!parsedMetadataHash.ContainsKey("Description") || String.IsNullOrWhiteSpace(parsedMetadataHash["Description"].ToString())) { message = "No description was provided in the script metadata. Script metadata must specify a version, author and description."; var ex = new ArgumentException(message); var InvalidScriptMetadata = new ErrorRecord(ex, "InvalidScriptMetadata", ErrorCategory.InvalidData, null); WriteError(InvalidScriptMetadata); return; } // remove '.ps1' extension from file name _pkgName = pkgFileOrDir.Name.Remove(pkgFileOrDir.Name.Length - 4); } else { _pkgName = pkgFileOrDir.Name; moduleManifestOrScriptPath = System.IO.Path.Combine(_path, _pkgName + ".psd1"); moduleFileInfo = new FileInfo(moduleManifestOrScriptPath); // Validate that there's a module manifest if (!File.Exists(moduleManifestOrScriptPath)) { var message = String.Format("No file with a .psd1 extension was found in {0}. Please specify a path to a valid modulemanifest.", moduleManifestOrScriptPath); var ex = new ArgumentException(message); var moduleManifestNotFound = new ErrorRecord(ex, "moduleManifestNotFound", ErrorCategory.ObjectNotFound, null); WriteError(moduleManifestNotFound); return; } // validate that the module manifest has correct data if (!IsValidModuleManifest(moduleManifestOrScriptPath)) { return; } } // Create a temp folder to push the nupkg to and delete it later string outputDir = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString()); if (!Directory.Exists(outputDir)) { try { Directory.CreateDirectory(outputDir); } catch (Exception e) { var ex = new ArgumentException(e.Message); var ErrorCreatingTempDir = new ErrorRecord(ex, "ErrorCreatingTempDir", ErrorCategory.InvalidData, null); WriteError(ErrorCreatingTempDir); return; } } try { Hashtable dependencies; // Create a nuspec // Right now parsedMetadataHash will be empty for modules and will contain metadata for scripts string nuspec = string.Empty; try { nuspec = CreateNuspec(outputDir, moduleFileInfo, out dependencies, parsedMetadataHash); } catch { var message = "Nuspec creation failed."; var ex = new ArgumentException(message); var nuspecCreationFailed = new ErrorRecord(ex, "NuspecCreationFailed", ErrorCategory.ObjectNotFound, null); WriteError(nuspecCreationFailed); return; } if (string.IsNullOrEmpty(nuspec)) { // nuspec creation failed. WriteDebug("Nuspec creation failed."); return; } // Find repository PSRepositoryInfo repository = RepositorySettings.Read(new[] { Repository }, out string[] errorList).FirstOrDefault(); if (repository == null) { var message = String.Format("The resource repository '{0}' is not a registered. Please run 'Register-PSResourceRepository' in order to publish to this repository.", Repository); var ex = new ArgumentException(message); var repositoryNotFound = new ErrorRecord(ex, "repositoryNotFound", ErrorCategory.ObjectNotFound, null); WriteError(repositoryNotFound); return; } string repositoryUrl = repository.Url.AbsoluteUri; // Check if dependencies already exist within the repo if: // 1) the resource to publish has dependencies and // 2) the -SkipDependenciesCheck flag is not passed in if (dependencies != null && !SkipDependenciesCheck) { // If error gets thrown, exit process record if (!CheckDependenciesExist(dependencies, repositoryUrl)) { return; } } if (isScript) { // copy the script file to the temp directory File.Copy(_path, System.IO.Path.Combine(outputDir, _pkgName + ".ps1"), true); } else { // Create subdirectory structure in temp folder foreach (string dir in System.IO.Directory.GetDirectories(_path, "*", System.IO.SearchOption.AllDirectories)) { var dirName = dir.Substring(_path.Length).Trim(_PathSeparators); System.IO.Directory.CreateDirectory(System.IO.Path.Combine(outputDir, dirName)); } // Copy files over to temp folder foreach (string fileNamePath in System.IO.Directory.GetFiles(_path, "*", System.IO.SearchOption.AllDirectories)) { var fileName = fileNamePath.Substring(_path.Length).Trim(_PathSeparators); // The user may have a .nuspec defined in the module directory // If that's the case, we will not use that file and use the .nuspec that is generated via PSGet // The .nuspec that is already in in the output directory is the one that was generated via the CreateNuspec method var newFilePath = System.IO.Path.Combine(outputDir, fileName); if (!File.Exists(newFilePath)) { System.IO.File.Copy(fileNamePath, newFilePath); } } } var outputNupkgDir = System.IO.Path.Combine(outputDir, "nupkg"); // pack into a nupkg try { if (!PackNupkg(outputDir, outputNupkgDir, nuspec)) { return; } } catch (Exception e) { var message = string.Format("Error packing into .nupkg: '{0}'.", e.Message); var ex = new ArgumentException(message); var ErrorPackingIntoNupkg = new ErrorRecord(ex, "ErrorPackingIntoNupkg", ErrorCategory.NotSpecified, null); WriteError(ErrorPackingIntoNupkg); // exit process record return; } PushNupkg(outputNupkgDir, repositoryUrl); } finally { WriteDebug(string.Format("Deleting temporary directory '{0}'", outputDir)); Directory.Delete(outputDir, recursive: true); } }
// This method calls iterates through repositories (by priority order) to search for the pkgs to install public void ProcessRepositories(string[] packageNames, string[] repository, bool trustRepository, PSCredential credential) { var listOfRepositories = RepositorySettings.Read(repository, out string[] _); List <string> packagesToInstall = packageNames.ToList(); var yesToAll = false; var noToAll = false; var repositoryIsNotTrusted = "Untrusted repository"; var queryInstallUntrustedPackage = "You are installing the modules from an untrusted repository. If you trust this repository, change its Trusted value by running the Set-PSResourceRepository cmdlet. Are you sure you want to install the PSresource from '{0}' ?"; foreach (var repo in listOfRepositories) { // If no more packages to install, then return if (!packagesToInstall.Any()) { return; } var sourceTrusted = false; string repoName = repo.Name; _cmdletPassedIn.WriteDebug(string.Format("Attempting to search for packages in '{0}'", repoName)); // Source is only trusted if it's set at the repository level to be trusted, -TrustRepository flag is true, -Force flag is true // OR the user issues trust interactively via console. if (repo.Trusted == false && !trustRepository && !_force) { _cmdletPassedIn.WriteDebug("Checking if untrusted repository should be used"); if (!(yesToAll || noToAll)) { // Prompt for installation of package from untrusted repository var message = string.Format(CultureInfo.InvariantCulture, queryInstallUntrustedPackage, repoName); sourceTrusted = _cmdletPassedIn.ShouldContinue(message, repositoryIsNotTrusted, true, ref yesToAll, ref noToAll); } } else { sourceTrusted = true; } if (sourceTrusted || yesToAll) { _cmdletPassedIn.WriteDebug("Untrusted repository accepted as trusted source."); // If it can't find the pkg in one repository, it'll look for it in the next repo in the list var isLocalRepo = repo.Url.AbsoluteUri.StartsWith(Uri.UriSchemeFile + Uri.SchemeDelimiter, StringComparison.OrdinalIgnoreCase); var findHelper = new FindHelper(_cancellationToken, _cmdletPassedIn); // Finds parent packages and dependencies IEnumerable <PSResourceInfo> pkgsFromRepoToInstall = findHelper.FindByResourceName( name: packageNames, type: ResourceType.None, version: _versionRange != null ? _versionRange.OriginalString : null, prerelease: _prerelease, tag: null, repository: new string[] { repoName }, credential: credential, includeDependencies: true); foreach (PSResourceInfo a in pkgsFromRepoToInstall) { var test = a; _cmdletPassedIn.WriteVerbose(a.Version.ToString()); } // Select the first package from each name group, which is guaranteed to be the latest version. // We should only have one version returned for each package name // e.g.: // PackageA (version 1.0) // PackageB (version 2.0) // PackageC (version 1.0) pkgsFromRepoToInstall = pkgsFromRepoToInstall.GroupBy( m => new { m.Name }).Select( group => group.First()).ToList(); if (!pkgsFromRepoToInstall.Any()) { _cmdletPassedIn.WriteVerbose(string.Format("None of the specified resources were found in the '{0}' repository.", repoName)); // Check in the next repository continue; } // Check to see if the pkgs (including dependencies) are already installed (ie the pkg is installed and the version satisfies the version range provided via param) if (!_reinstall) { // Removes all of the names that are already installed from the list of names to search for pkgsFromRepoToInstall = FilterByInstalledPkgs(pkgsFromRepoToInstall); } if (!pkgsFromRepoToInstall.Any()) { continue; } List <string> pkgsInstalled = InstallPackage(pkgsFromRepoToInstall, repoName, repo.Url.AbsoluteUri, credential, isLocalRepo); foreach (string name in pkgsInstalled) { packagesToInstall.Remove(name); } } } }
public IEnumerable <PSResourceInfo> FindByResourceName( string[] name, ResourceType type, string version, SwitchParameter prerelease, string[] tag, string[] repository, PSCredential credential, SwitchParameter includeDependencies) { _type = type; _version = version; _prerelease = prerelease; _tag = tag; _credential = credential; _includeDependencies = includeDependencies; Dbg.Assert(name.Length != 0, "Name length cannot be 0"); _pkgsLeftToFind = name.ToList(); List <PSRepositoryInfo> repositoriesToSearch; try { repositoriesToSearch = RepositorySettings.Read(repository, out string[] errorList); foreach (string error in errorList) { _cmdletPassedIn.WriteError(new ErrorRecord( new PSInvalidOperationException(error), "ErrorGettingSpecifiedRepo", ErrorCategory.InvalidOperation, this)); } } catch (Exception e) { _cmdletPassedIn.ThrowTerminatingError(new ErrorRecord( new PSInvalidOperationException(e.Message), "ErrorLoadingRepositoryStoreFile", ErrorCategory.InvalidArgument, this)); yield break; } // loop through repositoriesToSearch and if PSGallery add it to list with same priority as PSGallery repo for (int i = 0; i < repositoriesToSearch.Count; i++) { if (String.Equals(repositoriesToSearch[i].Name, _psGalleryRepoName, StringComparison.InvariantCultureIgnoreCase)) { // for PowerShellGallery, Module and Script resources have different endpoints so separate repositories have to be registered // with those endpoints in order for the NuGet APIs to search across both in the case where name includes '*' // detect if Script repository needs to be added and/or Module repository needs to be skipped Uri psGalleryScriptsUrl = new Uri("http://www.powershellgallery.com/api/v2/items/psscript/"); PSRepositoryInfo psGalleryScripts = new PSRepositoryInfo(_psGalleryScriptsRepoName, psGalleryScriptsUrl, repositoriesToSearch[i].Priority, false); if (_type == ResourceType.None) { _cmdletPassedIn.WriteDebug("Null Type provided, so add PSGalleryScripts repository"); repositoriesToSearch.Insert(i + 1, psGalleryScripts); } else if (_type != ResourceType.None && _type == ResourceType.Script) { _cmdletPassedIn.WriteDebug("Type Script provided, so add PSGalleryScripts and remove PSGallery (Modules only)"); repositoriesToSearch.Insert(i + 1, psGalleryScripts); repositoriesToSearch.RemoveAt(i); // remove PSGallery } } } for (int i = 0; i < repositoriesToSearch.Count && _pkgsLeftToFind.Any(); i++) { _cmdletPassedIn.WriteDebug(string.Format("Searching in repository {0}", repositoriesToSearch[i].Name)); foreach (var pkg in SearchFromRepository( repositoryName: repositoriesToSearch[i].Name, repositoryUrl: repositoriesToSearch[i].Url)) { yield return(pkg); } } }
public List <PSResourceInfo> FindByResourceName( string[] name, ResourceType type, string version, SwitchParameter prerelease, string[] tag, string[] repository, PSCredential credential, SwitchParameter includeDependencies) { _type = type; _version = version; _prerelease = prerelease; _tag = tag; _credential = credential; _includeDependencies = includeDependencies; List <PSResourceInfo> foundPackages = new List <PSResourceInfo>(); if (name.Length == 0) { return(foundPackages); } _pkgsLeftToFind = name.ToList(); // Error out if repository array of names to be searched contains wildcards. if (repository != null) { repository = Utils.ProcessNameWildcards(repository, out string[] errorMsgs, out _repositoryNameContainsWildcard); foreach (string error in errorMsgs) { _cmdletPassedIn.WriteError(new ErrorRecord( new PSInvalidOperationException(error), "ErrorFilteringNamesForUnsupportedWildcards", ErrorCategory.InvalidArgument, this)); } } // Get repositories to search. List <PSRepositoryInfo> repositoriesToSearch; try { repositoriesToSearch = RepositorySettings.Read(repository, out string[] errorList); foreach (string error in errorList) { _cmdletPassedIn.WriteError(new ErrorRecord( new PSInvalidOperationException(error), "ErrorGettingSpecifiedRepo", ErrorCategory.InvalidOperation, this)); } } catch (Exception e) { _cmdletPassedIn.ThrowTerminatingError(new ErrorRecord( new PSInvalidOperationException(e.Message), "ErrorLoadingRepositoryStoreFile", ErrorCategory.InvalidArgument, this)); return(foundPackages); } // Loop through repositoriesToSearch and if PSGallery or PoshTestGallery add its Scripts endpoint repo // to list with same priority as PSGallery repo. // This special casing is done to handle PSGallery and PoshTestGallery having 2 endpoints currently for different resources. for (int i = 0; i < repositoriesToSearch.Count; i++) { if (String.Equals(repositoriesToSearch[i].Uri.AbsoluteUri, _psGalleryUri, StringComparison.InvariantCultureIgnoreCase)) { // special case: for PowerShellGallery, Module and Script resources have different endpoints so separate repositories have to be registered // with those endpoints in order for the NuGet APIs to search across both in the case where name includes '*' // detect if Script repository needs to be added and/or Module repository needs to be skipped Uri psGalleryScriptsUri = new Uri("http://www.powershellgallery.com/api/v2/items/psscript/"); PSRepositoryInfo psGalleryScripts = new PSRepositoryInfo(_psGalleryScriptsRepoName, psGalleryScriptsUri, repositoriesToSearch[i].Priority, trusted: false, credentialInfo: null); if (_type == ResourceType.None) { _cmdletPassedIn.WriteVerbose("Null Type provided, so add PSGalleryScripts repository"); repositoriesToSearch.Insert(i + 1, psGalleryScripts); } else if (_type != ResourceType.None && _type == ResourceType.Script) { _cmdletPassedIn.WriteVerbose("Type Script provided, so add PSGalleryScripts and remove PSGallery (Modules only) from search consideration"); repositoriesToSearch.Insert(i + 1, psGalleryScripts); repositoriesToSearch.RemoveAt(i); // remove PSGallery } } else if (String.Equals(repositoriesToSearch[i].Uri.AbsoluteUri, _poshTestGalleryUri, StringComparison.InvariantCultureIgnoreCase)) { // special case: for PoshTestGallery, Module and Script resources have different endpoints so separate repositories have to be registered // with those endpoints in order for the NuGet APIs to search across both in the case where name includes '*' // detect if Script repository needs to be added and/or Module repository needs to be skipped Uri poshTestGalleryScriptsUri = new Uri("https://www.poshtestgallery.com/api/v2/items/psscript/"); PSRepositoryInfo poshTestGalleryScripts = new PSRepositoryInfo(_poshTestGalleryScriptsRepoName, poshTestGalleryScriptsUri, repositoriesToSearch[i].Priority, trusted: false, credentialInfo: null); if (_type == ResourceType.None) { _cmdletPassedIn.WriteVerbose("Null Type provided, so add PoshTestGalleryScripts repository"); repositoriesToSearch.Insert(i + 1, poshTestGalleryScripts); } else if (_type != ResourceType.None && _type == ResourceType.Script) { _cmdletPassedIn.WriteVerbose("Type Script provided, so add PoshTestGalleryScripts and remove PoshTestGallery (Modules only) from search consideration"); repositoriesToSearch.Insert(i + 1, poshTestGalleryScripts); repositoriesToSearch.RemoveAt(i); // remove PoshTestGallery } } } for (int i = 0; i < repositoriesToSearch.Count && _pkgsLeftToFind.Any(); i++) { _cmdletPassedIn.WriteVerbose(string.Format("Searching in repository {0}", repositoriesToSearch[i].Name)); foreach (var pkg in SearchFromRepository( repositoryName: repositoriesToSearch[i].Name, repositoryUri: repositoriesToSearch[i].Uri, repositoryCredentialInfo: repositoriesToSearch[i].CredentialInfo)) { foundPackages.Add(pkg); } } return(foundPackages); }