Пример #1
0
 public void WriteVerbose(string text)
 {
     _cmd?.WriteVerbose(text);
 }
Пример #2
0
        public Dictionary <string, List <string> > CheckRuleExtension(string[] path, PSCmdlet cmdlet)
        {
            Dictionary <string, List <string> > results = new Dictionary <string, List <string> >();

            List <string> invalidPaths  = new List <string>();
            List <string> validDllPaths = new List <string>();
            List <string> validModPaths = new List <string>();

            // Gets valid module names
            foreach (string childPath in path)
            {
                try
                {
                    cmdlet.WriteVerbose(string.Format(CultureInfo.CurrentCulture, Strings.CheckModuleName, childPath));

                    string resolvedPath = string.Empty;

                    // Users may provide a valid module path or name,
                    // We have to identify the childPath is really a directory or just a module name.
                    // You can also consider following two commands.
                    //   Get-ScriptAnalyzerRule -RuleExtension "ContosoAnalyzerRules"
                    //   Get-ScriptAnalyzerRule -RuleExtension "%USERPROFILE%\WindowsPowerShell\Modules\ContosoAnalyzerRules"
                    if (Path.GetDirectoryName(childPath) == string.Empty)
                    {
                        resolvedPath = childPath;
                    }
                    else
                    {
                        resolvedPath = cmdlet.SessionState.Path
                                       .GetResolvedPSPathFromPSPath(childPath).First().ToString();
                    }

                    using (System.Management.Automation.PowerShell posh =
                               System.Management.Automation.PowerShell.Create())
                    {
                        string       script     = string.Format(CultureInfo.CurrentCulture, "Get-Module -Name '{0}' -ListAvailable", resolvedPath);
                        PSModuleInfo moduleInfo = posh.AddScript(script).Invoke <PSModuleInfo>().First();

                        // Adds original path, otherwise path.Except<string>(validModPaths) will fail.
                        // It's possible that user can provide something like this:
                        // "..\..\..\ScriptAnalyzer.UnitTest\modules\CommunityAnalyzerRules\CommunityAnalyzerRules.psd1"
                        if (moduleInfo.ExportedFunctions.Count > 0)
                        {
                            validModPaths.Add(childPath);
                        }
                    }
                }
                catch
                {
                    // User may provide an invalid module name, like c:\temp.
                    // It's a invalid name for a Windows PowerShell module,
                    // But we need test it further since we allow user to provide a folder to extend rules.
                    // You can also consider following two commands.
                    //   Get-ScriptAnalyzerRule -RuleExtension "ContosoAnalyzerRules", "C:\Temp\ExtendScriptAnalyzerRules.dll"
                    //   Get-ScriptAnalyzerRule -RuleExtension "ContosoAnalyzerRules", "C:\Temp\"
                    continue;
                }
            }

            // Gets valid dll paths
            foreach (string childPath in path.Except <string>(validModPaths))
            {
                try
                {
                    string resolvedPath = cmdlet.SessionState.Path
                                          .GetResolvedPSPathFromPSPath(childPath).First().ToString();

                    cmdlet.WriteDebug(string.Format(CultureInfo.CurrentCulture, Strings.CheckAssemblyFile, resolvedPath));

                    if (String.Equals(Path.GetExtension(resolvedPath), ".dll", StringComparison.OrdinalIgnoreCase))
                    {
                        if (!File.Exists(resolvedPath))
                        {
                            invalidPaths.Add(resolvedPath);
                            continue;
                        }
                    }
                    else
                    {
                        if (!Directory.Exists(resolvedPath))
                        {
                            invalidPaths.Add(resolvedPath);
                            continue;
                        }
                    }

                    validDllPaths.Add(resolvedPath);
                }
                catch
                {
                    invalidPaths.Add(childPath);
                }
            }

            // Resloves relative paths.
            try
            {
                for (int i = 0; i < validModPaths.Count; i++)
                {
                    validModPaths[i] = cmdlet.SessionState.Path
                                       .GetResolvedPSPathFromPSPath(validModPaths[i]).First().ToString();
                }
                for (int i = 0; i < validDllPaths.Count; i++)
                {
                    validDllPaths[i] = cmdlet.SessionState.Path
                                       .GetResolvedPSPathFromPSPath(validDllPaths[i]).First().ToString();
                }
            }
            catch
            {
                // If GetResolvedPSPathFromPSPath failed. We can safely ignore the exception.
                // Because GetResolvedPSPathFromPSPath always fails when trying to resolve a module name.
            }

            // Returns valid rule extensions
            results.Add("InvalidPaths", invalidPaths);
            results.Add("ValidModPaths", validModPaths);
            results.Add("ValidDllPaths", validDllPaths);

            return(results);
        }
Пример #3
0
 public static void WriteFromHelper(PSCmdlet cmdlet, string message)
 {
     cmdlet.WriteVerbose(message);
 }
Пример #4
0
        public static void WriteVerbose(this PSCmdlet cmdlet, string format, params object[] args)
        {
            var text = string.Format(CultureInfo.InvariantCulture, format, args);

            cmdlet.WriteVerbose(text);
        }
Пример #5
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;

            //determine if repository array of names of repositories input to be searched contains wildcard
            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));
                }
            }

            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 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))
                {
                    yield return(pkg);
                }
            }
        }