private List <PSRepositoryInfo> RepositoriesParameterSetHelper()
        {
            List <PSRepositoryInfo> reposAddedFromHashTable = new List <PSRepositoryInfo>();

            foreach (Hashtable repo in Repositories)
            {
                if (repo.ContainsKey(PSGalleryRepoName))
                {
                    if (repo.ContainsKey("Name") || repo.ContainsKey("Uri") || repo.ContainsKey("CredentialInfo"))
                    {
                        WriteError(new ErrorRecord(
                                       new PSInvalidOperationException("Repository hashtable cannot contain PSGallery key with -Name, -Uri and/or -CredentialInfo key value pairs"),
                                       "NotProvideNameUriCredentialInfoForPSGalleryRepositoriesParameterSetRegistration",
                                       ErrorCategory.InvalidArgument,
                                       this));
                        continue;
                    }

                    try
                    {
                        WriteVerbose("(RepositoriesParameterSet): on repo: PSGallery. Registers PSGallery repository");
                        reposAddedFromHashTable.Add(PSGalleryParameterSetHelper(
                                                        repo.ContainsKey("Priority") ? (int)repo["Priority"] : defaultPriority,
                                                        repo.ContainsKey("Trusted") ? (bool)repo["Trusted"] : defaultTrusted));
                    }
                    catch (Exception e)
                    {
                        WriteError(new ErrorRecord(
                                       new PSInvalidOperationException(e.Message),
                                       "ErrorParsingIndividualRepoPSGallery",
                                       ErrorCategory.InvalidArgument,
                                       this));
                    }
                }
                else
                {
                    PSRepositoryInfo parsedRepoAdded = RepoValidationHelper(repo);
                    if (parsedRepoAdded != null)
                    {
                        reposAddedFromHashTable.Add(parsedRepoAdded);
                    }
                }
            }

            return(reposAddedFromHashTable);
        }
Exemplo n.º 2
0
        private List <PSRepositoryInfo> RepositoriesParameterSetHelper()
        {
            List <PSRepositoryInfo> reposUpdatedFromHashtable = new List <PSRepositoryInfo>();

            foreach (Hashtable repo in Repository)
            {
                if (!repo.ContainsKey("Name") || repo["Name"] == null || String.IsNullOrEmpty(repo["Name"].ToString()))
                {
                    WriteError(new ErrorRecord(
                                   new PSInvalidOperationException("Repository hashtable must contain Name key value pair"),
                                   "NullNameForRepositoriesParameterSetRepo",
                                   ErrorCategory.InvalidArgument,
                                   this));
                    continue;
                }

                PSRepositoryInfo parsedRepoAdded = RepoValidationHelper(repo);
                if (parsedRepoAdded != null)
                {
                    reposUpdatedFromHashtable.Add(parsedRepoAdded);
                }
            }
            return(reposUpdatedFromHashtable);
        }
Exemplo n.º 3
0
        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);
            }
        }
Exemplo n.º 4
0
        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);
                }
            }
        }
Exemplo n.º 5
0
        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);
        }