File size: 13,591 Bytes
8c763fb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Xml;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation
{
internal class PSClassHelpProvider : HelpProviderWithCache
{
/// <summary>
/// Constructor for PSClassHelpProvider.
/// </summary>
internal PSClassHelpProvider(HelpSystem helpSystem)
: base(helpSystem)
{
_context = helpSystem.ExecutionContext;
}
/// <summary>
/// Execution context of the HelpSystem.
/// </summary>
private readonly ExecutionContext _context;
/// <summary>
/// This is a hashtable to track which help files are loaded already.
///
/// This will avoid one help file getting loaded again and again.
/// </summary>
private readonly Hashtable _helpFiles = new Hashtable();
[TraceSource("PSClassHelpProvider", "PSClassHelpProvider")]
private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("PSClassHelpProvider", "PSClassHelpProvider");
#region common properties
/// <summary>
/// Name of the Help Provider.
/// </summary>
internal override string Name
{
get { return "Powershell Class Help Provider"; }
}
/// <summary>
/// Supported Help Categories.
/// </summary>
internal override HelpCategory HelpCategory
{
get { return Automation.HelpCategory.Class; }
}
#endregion
/// <summary>
/// Override SearchHelp to find a class module with help matching a pattern.
/// </summary>
/// <param name="helpRequest">Help request.</param>
/// <param name="searchOnlyContent">Not used.</param>
/// <returns></returns>
internal override IEnumerable<HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent)
{
Debug.Assert(helpRequest != null, "helpRequest cannot be null.");
string target = helpRequest.Target;
Collection<string> patternList = new Collection<string>();
bool decoratedSearch = !WildcardPattern.ContainsWildcardCharacters(helpRequest.Target);
if (decoratedSearch)
{
patternList.Add("*" + target + "*");
}
else
patternList.Add(target);
foreach (string pattern in patternList)
{
PSClassSearcher searcher = new PSClassSearcher(pattern, useWildCards: true, _context);
foreach (var helpInfo in GetHelpInfo(searcher))
{
if (helpInfo != null)
yield return helpInfo;
}
}
}
/// <summary>
/// Override ExactMatchHelp to find the matching class module matching help request.
/// </summary>
/// <param name="helpRequest">Help Request for the search.</param>
/// <returns>Enumerable of HelpInfo objects.</returns>
internal override IEnumerable<HelpInfo> ExactMatchHelp(HelpRequest helpRequest)
{
Debug.Assert(helpRequest != null, "helpRequest cannot be null.");
if ((helpRequest.HelpCategory & Automation.HelpCategory.Class) == 0)
{
yield return null;
}
PSClassSearcher searcher = new PSClassSearcher(helpRequest.Target, useWildCards: false, _context);
foreach (var helpInfo in GetHelpInfo(searcher))
{
if (helpInfo != null)
{
yield return helpInfo;
}
}
}
/// <summary>
/// Get the help in for the PS Class Info. ///
/// </summary>
/// <param name="searcher">Searcher for PS Classes.</param>
/// <returns>Next HelpInfo object.</returns>
private IEnumerable<HelpInfo> GetHelpInfo(PSClassSearcher searcher)
{
while (searcher.MoveNext())
{
PSClassInfo current = ((IEnumerator<PSClassInfo>)searcher).Current;
string moduleName = current.Module.Name;
string moduleDir = current.Module.ModuleBase;
if (!string.IsNullOrEmpty(moduleName) && !string.IsNullOrEmpty(moduleDir))
{
string helpFileToFind = moduleName + "-Help.xml";
string helpFileName = null;
Collection<string> searchPaths = new Collection<string>();
searchPaths.Add(moduleDir);
string externalHelpFile = current.HelpFile;
if (!string.IsNullOrEmpty(externalHelpFile))
{
FileInfo helpFileInfo = new FileInfo(externalHelpFile);
DirectoryInfo dirToSearch = helpFileInfo.Directory;
if (dirToSearch.Exists)
{
searchPaths.Add(dirToSearch.FullName);
helpFileToFind = helpFileInfo.Name; // If external help file is specified. Then use it.
}
}
HelpInfo helpInfo = GetHelpInfoFromHelpFile(current, helpFileToFind, searchPaths, true, out helpFileName);
if (helpInfo != null)
{
yield return helpInfo;
}
}
}
}
/// <summary>
/// Check whether a HelpItems node indicates that the help content is
/// authored using maml schema.
///
/// This covers two cases:
/// a. If the help file has an extension .maml.
/// b. If HelpItems node (which should be the top node of any command help file)
/// has an attribute "schema" with value "maml", its content is in maml
/// schema.
/// </summary>
/// <param name="helpFile">File name.</param>
/// <param name="helpItemsNode">Nodes to check.</param>
/// <returns></returns>
internal static bool IsMamlHelp(string helpFile, XmlNode helpItemsNode)
{
Debug.Assert(!string.IsNullOrEmpty(helpFile), "helpFile cannot be null.");
if (helpFile.EndsWith(".maml", StringComparison.OrdinalIgnoreCase))
return true;
if (helpItemsNode.Attributes == null)
return false;
foreach (XmlNode attribute in helpItemsNode.Attributes)
{
if (attribute.Name.Equals("schema", StringComparison.OrdinalIgnoreCase)
&& attribute.Value.Equals("maml", StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
#region private methods
private HelpInfo GetHelpInfoFromHelpFile(PSClassInfo classInfo, string helpFileToFind, Collection<string> searchPaths, bool reportErrors, out string helpFile)
{
Dbg.Assert(classInfo != null, "Caller should verify that classInfo != null");
Dbg.Assert(helpFileToFind != null, "Caller should verify that helpFileToFind != null");
helpFile = MUIFileSearcher.LocateFile(helpFileToFind, searchPaths);
if (!File.Exists(helpFile))
return null;
if (!string.IsNullOrEmpty(helpFile))
{
// Load the help file only once. Then use it from the cache.
if (!_helpFiles.Contains(helpFile))
{
LoadHelpFile(helpFile, helpFile, classInfo.Name, reportErrors);
}
return GetFromPSClassHelpCache(helpFile, Automation.HelpCategory.Class);
}
return null;
}
/// <summary>
/// Gets the HelpInfo object corresponding to the command.
/// </summary>
/// <param name="helpFileIdentifier">Help file identifier (either name of PSSnapIn or simply full path to help file).</param>
/// <param name="helpCategory">Help Category for search.</param>
/// <returns>HelpInfo object.</returns>
private HelpInfo GetFromPSClassHelpCache(string helpFileIdentifier, HelpCategory helpCategory)
{
Debug.Assert(!string.IsNullOrEmpty(helpFileIdentifier), "helpFileIdentifier should not be null or empty.");
HelpInfo result = GetCache(helpFileIdentifier);
if (result != null)
{
MamlClassHelpInfo original = (MamlClassHelpInfo)result;
result = original.Copy(helpCategory);
}
return result;
}
private void LoadHelpFile(string helpFile, string helpFileIdentifier, string commandName, bool reportErrors)
{
Exception e = null;
try
{
LoadHelpFile(helpFile, helpFileIdentifier);
}
catch (IOException ioException)
{
e = ioException;
}
catch (System.Security.SecurityException securityException)
{
e = securityException;
}
catch (XmlException xmlException)
{
e = xmlException;
}
catch (NotSupportedException notSupportedException)
{
e = notSupportedException;
}
catch (UnauthorizedAccessException unauthorizedAccessException)
{
e = unauthorizedAccessException;
}
catch (InvalidOperationException invalidOperationException)
{
e = invalidOperationException;
}
if (e != null)
s_tracer.WriteLine("Error occurred in PSClassHelpProvider {0}", e.Message);
if (reportErrors && (e != null))
{
ReportHelpFileError(e, commandName, helpFile);
}
}
/// <summary>
/// Load help file for HelpInfo objects. The HelpInfo objects will be
/// put into help cache.
/// </summary>
/// <remarks>
/// 1. Needs to pay special attention about error handling in this function.
/// Common errors include: file not found and invalid xml. None of these error
/// should cause help search to stop.
/// 2. a helpfile cache is used to avoid same file got loaded again and again.
/// </remarks>
private void LoadHelpFile(string helpFile, string helpFileIdentifier)
{
Dbg.Assert(!string.IsNullOrEmpty(helpFile), "HelpFile cannot be null or empty.");
Dbg.Assert(!string.IsNullOrEmpty(helpFileIdentifier), "helpFileIdentifier cannot be null or empty.");
XmlDocument doc = InternalDeserializer.LoadUnsafeXmlDocument(
new FileInfo(helpFile),
false, /* ignore whitespace, comments, etc. */
null); /* default maxCharactersInDocument */
// Add this file into _helpFiles hashtable to prevent it to be loaded again.
_helpFiles[helpFile] = 0;
XmlNode helpItemsNode = null;
if (doc.HasChildNodes)
{
for (int i = 0; i < doc.ChildNodes.Count; i++)
{
XmlNode node = doc.ChildNodes[i];
if (node.NodeType == XmlNodeType.Element && string.Equals(node.LocalName, "helpItems", StringComparison.OrdinalIgnoreCase))
{
helpItemsNode = node;
break;
}
}
}
if (helpItemsNode == null)
{
s_tracer.WriteLine("Unable to find 'helpItems' element in file {0}", helpFile);
return;
}
bool isMaml = IsMamlHelp(helpFile, helpItemsNode);
using (this.HelpSystem.Trace(helpFile))
{
if (helpItemsNode.HasChildNodes)
{
for (int i = 0; i < helpItemsNode.ChildNodes.Count; i++)
{
XmlNode node = helpItemsNode.ChildNodes[i];
string nodeLocalName = node.LocalName;
bool isClass = (string.Equals(nodeLocalName, "class", StringComparison.OrdinalIgnoreCase));
if (node.NodeType == XmlNodeType.Element && isClass)
{
MamlClassHelpInfo helpInfo = null;
if (isMaml)
{
if (isClass)
helpInfo = MamlClassHelpInfo.Load(node, HelpCategory.Class);
}
if (helpInfo != null)
{
this.HelpSystem.TraceErrors(helpInfo.Errors);
AddCache(helpFileIdentifier, helpInfo);
}
}
}
}
}
}
#endregion
}
}
|