File size: 58,920 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 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 | // 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.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Management.Automation.Internal;
using System.Management.Automation.Runspaces;
using System.Xml;
using Dbg = System.Management.Automation.Diagnostics;
using System.Management.Automation.Help;
using System.Reflection;
namespace System.Management.Automation
{
/// <summary>
/// Class CommandHelpProvider implement the help provider for commands.
/// </summary>
/// <remarks>
/// Command Help information are stored in 'help.xml' files. Location of these files
/// can be found from through the engine execution context.
/// </remarks>
internal class CommandHelpProvider : HelpProviderWithCache
{
/// <summary>
/// Constructor for CommandHelpProvider.
/// </summary>
internal CommandHelpProvider(HelpSystem helpSystem) : base(helpSystem)
{
_context = helpSystem.ExecutionContext;
}
/// <summary>
/// </summary>
static CommandHelpProvider()
{
s_engineModuleHelpFileCache.Add("Microsoft.PowerShell.Diagnostics", "Microsoft.PowerShell.Commands.Diagnostics.dll-Help.xml");
s_engineModuleHelpFileCache.Add("Microsoft.PowerShell.Core", "System.Management.Automation.dll-Help.xml");
s_engineModuleHelpFileCache.Add("Microsoft.PowerShell.Utility", "Microsoft.PowerShell.Commands.Utility.dll-Help.xml");
s_engineModuleHelpFileCache.Add("Microsoft.PowerShell.Host", "Microsoft.PowerShell.ConsoleHost.dll-Help.xml");
s_engineModuleHelpFileCache.Add("Microsoft.PowerShell.Management", "Microsoft.PowerShell.Commands.Management.dll-Help.xml");
s_engineModuleHelpFileCache.Add("Microsoft.PowerShell.Security", "Microsoft.PowerShell.Security.dll-Help.xml");
s_engineModuleHelpFileCache.Add("Microsoft.WSMan.Management", "Microsoft.Wsman.Management.dll-Help.xml");
}
private static readonly Dictionary<string, string> s_engineModuleHelpFileCache = new Dictionary<string, string>();
private readonly ExecutionContext _context;
#region Common Properties
/// <summary>
/// Name of this provider.
/// </summary>
/// <value>Name of this provider</value>
internal override string Name
{
get
{
return "Command Help Provider";
}
}
/// <summary>
/// Help category for this provider, which is a constant: HelpCategory.Command.
/// </summary>
/// <value>Help category for this provider</value>
internal override HelpCategory HelpCategory
{
get
{
return
HelpCategory.Alias |
HelpCategory.Cmdlet;
}
}
#endregion
#region Help Provider Interface
private static void GetModulePaths(CommandInfo commandInfo, out string moduleName, out string moduleDir, out string nestedModulePath)
{
Dbg.Assert(commandInfo != null, "Caller should verify that commandInfo != null");
CmdletInfo cmdletInfo = commandInfo as CmdletInfo;
IScriptCommandInfo scriptCommandInfo = commandInfo as IScriptCommandInfo;
string cmdNameWithoutPrefix = null;
bool testWithoutPrefix = false;
moduleName = null;
moduleDir = null;
nestedModulePath = null;
if (commandInfo.Module != null)
{
moduleName = commandInfo.Module.Name;
moduleDir = commandInfo.Module.ModuleBase;
if (!string.IsNullOrEmpty(commandInfo.Prefix))
{
testWithoutPrefix = true;
cmdNameWithoutPrefix = Microsoft.PowerShell.Commands.ModuleCmdletBase.RemovePrefixFromCommandName(commandInfo.Name, commandInfo.Prefix);
}
if (commandInfo.Module.NestedModules != null)
{
foreach (PSModuleInfo nestedModule in commandInfo.Module.NestedModules)
{
if (cmdletInfo != null &&
(nestedModule.ExportedCmdlets.ContainsKey(commandInfo.Name) ||
(testWithoutPrefix && nestedModule.ExportedCmdlets.ContainsKey(cmdNameWithoutPrefix))))
{
nestedModulePath = nestedModule.Path;
break;
}
else if (scriptCommandInfo != null &&
(nestedModule.ExportedFunctions.ContainsKey(commandInfo.Name) ||
(testWithoutPrefix && nestedModule.ExportedFunctions.ContainsKey(cmdNameWithoutPrefix))))
{
nestedModulePath = nestedModule.Path;
break;
}
}
}
}
}
private static string GetHelpName(CommandInfo commandInfo)
{
Dbg.Assert(commandInfo != null, "Caller should verify that commandInfo != null");
CmdletInfo cmdletInfo = commandInfo as CmdletInfo;
if (cmdletInfo != null)
{
return cmdletInfo.FullName;
}
return commandInfo.Name;
}
private HelpInfo GetHelpInfoFromHelpFile(CommandInfo commandInfo, string helpFileToFind, Collection<string> searchPaths, bool reportErrors, out string helpFile)
{
Dbg.Assert(commandInfo != null, "Caller should verify that commandInfo != null");
Dbg.Assert(helpFileToFind != null, "Caller should verify that helpFileToFind != null");
CmdletInfo cmdletInfo = commandInfo as CmdletInfo;
IScriptCommandInfo scriptCommandInfo = commandInfo as IScriptCommandInfo;
HelpInfo result = null;
helpFile = MUIFileSearcher.LocateFile(helpFileToFind, searchPaths);
if (!string.IsNullOrEmpty(helpFile))
{
if (!_helpFiles.Contains(helpFile))
{
if (cmdletInfo != null)
{
LoadHelpFile(helpFile, cmdletInfo.ModuleName, cmdletInfo.Name, reportErrors);
}
else if (scriptCommandInfo != null)
{
LoadHelpFile(helpFile, helpFile, commandInfo.Name, reportErrors);
}
}
if (cmdletInfo != null)
{
result = GetFromCommandCacheOrCmdletInfo(cmdletInfo);
}
else if (scriptCommandInfo != null)
{
result = GetFromCommandCache(helpFile, commandInfo);
}
}
return result;
}
[SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", Justification = "TestUri is created only to check for source helpUriFromDotLink errors.")]
private HelpInfo GetHelpInfo(CommandInfo commandInfo, bool reportErrors, bool searchOnlyContent)
{
Dbg.Assert(commandInfo != null, "Caller should verify that commandInfo != null");
HelpInfo result = null; // The help result
string helpFile = null; // The file that contains the help info
string helpUri = null;
string helpUriFromDotLink = null;
CmdletInfo cmdletInfo = commandInfo as CmdletInfo;
IScriptCommandInfo scriptCommandInfo = commandInfo as IScriptCommandInfo;
FunctionInfo functionInfo = commandInfo as FunctionInfo;
bool isCmdlet = cmdletInfo != null;
bool isScriptCommand = scriptCommandInfo != null;
bool isFunction = functionInfo != null;
string moduleName = null;
string moduleDir = null;
string nestedModulePath = null;
// When InternalTestHooks.BypassOnlineHelpRetrieval is enable, we force get-help to generate a metadata
// driven object, which includes a helpUri that points to the fwlink defined in the cmdlet code.
// This means that we are not going to load the help content from the GetFromCommandCache and
// we are not going to read the help file.
// Only gets help for Cmdlet or script command
if (!isCmdlet && !isScriptCommand)
return null;
// Check if the help of the command is already in the cache.
// If not, try load the file specified by HelpFile property and retrieve help.
if (isCmdlet && !InternalTestHooks.BypassOnlineHelpRetrieval)
{
result = GetFromCommandCache(cmdletInfo.ModuleName, cmdletInfo.Name, cmdletInfo.HelpCategory);
if (result == null)
{
// Try load the help file specified by CmdletInfo.HelpFile property
helpFile = FindHelpFile(cmdletInfo);
if (!string.IsNullOrEmpty(helpFile) && !_helpFiles.Contains(helpFile))
{
LoadHelpFile(helpFile, cmdletInfo.ModuleName, cmdletInfo.Name, reportErrors);
}
result = GetFromCommandCacheOrCmdletInfo(cmdletInfo);
}
}
else if (isFunction)
{
// Try load the help file specified by FunctionInfo.HelpFile property
helpFile = functionInfo.HelpFile;
if (!string.IsNullOrEmpty(helpFile))
{
if (!_helpFiles.Contains(helpFile))
{
LoadHelpFile(helpFile, helpFile, commandInfo.Name, reportErrors);
}
result = GetFromCommandCache(helpFile, commandInfo);
}
}
// For scripts, try to retrieve the help from the file specified by .ExternalHelp directive
if (result == null && isScriptCommand)
{
ScriptBlock sb = null;
try
{
sb = scriptCommandInfo.ScriptBlock;
}
catch (RuntimeException)
{
// parsing errors should not block searching for help
return null;
}
if (sb != null)
{
helpFile = null;
// searchOnlyContent == true means get-help is looking into the content, in this case we dont
// want to download the content from the remote machine. Reason: In Exchange scenario there
// are ~700 proxy commands, downloading help for all the commands and searching in that
// content takes a lot of time (in the order of 30 minutes) for their scenarios.
result = sb.GetHelpInfo(_context, commandInfo, searchOnlyContent, HelpSystem.ScriptBlockTokenCache,
out helpFile, out helpUriFromDotLink);
if (!string.IsNullOrEmpty(helpUriFromDotLink))
{
try
{
Uri testUri = new Uri(helpUriFromDotLink);
helpUri = helpUriFromDotLink;
}
catch (UriFormatException)
{
// Do not add if helpUriFromDotLink is not a URI
}
}
if (result != null)
{
Uri uri = result.GetUriForOnlineHelp();
if (uri != null)
{
helpUri = uri.ToString();
}
}
if (!string.IsNullOrEmpty(helpFile) && !InternalTestHooks.BypassOnlineHelpRetrieval)
{
if (!_helpFiles.Contains(helpFile))
{
LoadHelpFile(helpFile, helpFile, commandInfo.Name, reportErrors);
}
result = GetFromCommandCache(helpFile, commandInfo) ?? result;
}
}
}
// If the above fails to get help, try search for a file called <ModuleName>-Help.xml
// in the appropriate UI culture subfolder of ModuleBase, and retrieve help
// If still not able to get help, try search for a file called <NestedModuleName>-Help.xml
// under the ModuleBase and the NestedModule's directory, and retrieve help
if (result == null && !InternalTestHooks.BypassOnlineHelpRetrieval)
{
// Get the name and ModuleBase directory of the command's module
// and the nested module that implements the command
GetModulePaths(commandInfo, out moduleName, out moduleDir, out nestedModulePath);
var userHomeHelpPath = HelpUtils.GetUserHomeHelpSearchPath();
Collection<string> searchPaths = new Collection<string>() { userHomeHelpPath };
if (!string.IsNullOrEmpty(moduleDir))
{
searchPaths.Add(moduleDir);
}
if (!string.IsNullOrEmpty(userHomeHelpPath) && !string.IsNullOrEmpty(moduleName))
{
searchPaths.Add(Path.Combine(userHomeHelpPath, moduleName));
}
if (!string.IsNullOrEmpty(moduleName) && !string.IsNullOrEmpty(moduleDir))
{
// Search for <ModuleName>-Help.xml under ModuleBase folder
string helpFileToFind = moduleName + "-Help.xml";
result = GetHelpInfoFromHelpFile(commandInfo, helpFileToFind, searchPaths, reportErrors, out helpFile);
}
if (result == null && !string.IsNullOrEmpty(nestedModulePath))
{
// Search for <NestedModuleName>-Help.xml under both ModuleBase and NestedModule's directory
searchPaths.Add(Path.GetDirectoryName(nestedModulePath));
string helpFileToFind = Path.GetFileName(nestedModulePath) + "-Help.xml";
result = GetHelpInfoFromHelpFile(commandInfo, helpFileToFind, searchPaths, reportErrors, out helpFile);
}
}
// Set the HelpFile property to the file that contains the help content
if (result != null && !string.IsNullOrEmpty(helpFile))
{
if (isCmdlet)
{
cmdletInfo.HelpFile = helpFile;
}
else if (isFunction)
{
functionInfo.HelpFile = helpFile;
}
}
// If the above fails to get help, construct an HelpInfo object using the syntax and definition of the command
if (result == null)
{
if (commandInfo.CommandType == CommandTypes.ExternalScript ||
commandInfo.CommandType == CommandTypes.Script)
{
result = SyntaxHelpInfo.GetHelpInfo(commandInfo.Name, commandInfo.Syntax, commandInfo.HelpCategory);
}
else
{
PSObject helpInfo = Help.DefaultCommandHelpObjectBuilder.GetPSObjectFromCmdletInfo(commandInfo);
helpInfo.TypeNames.Clear();
helpInfo.TypeNames.Add(DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp);
helpInfo.TypeNames.Add("CmdletHelpInfo");
helpInfo.TypeNames.Add("HelpInfo");
result = new MamlCommandHelpInfo(helpInfo, commandInfo.HelpCategory);
}
}
if (result != null)
{
if (isScriptCommand && result.GetUriForOnlineHelp() == null)
{
if (!string.IsNullOrEmpty(commandInfo.CommandMetadata.HelpUri))
{
DefaultCommandHelpObjectBuilder.AddRelatedLinksProperties(result.FullHelp, commandInfo.CommandMetadata.HelpUri);
}
else if (!string.IsNullOrEmpty(helpUri))
{
DefaultCommandHelpObjectBuilder.AddRelatedLinksProperties(result.FullHelp, helpUri);
}
}
if (isCmdlet && result.FullHelp.Properties["PSSnapIn"] == null)
{
result.FullHelp.Properties.Add(new PSNoteProperty("PSSnapIn", cmdletInfo.PSSnapIn));
}
if (result.FullHelp.Properties["ModuleName"] == null)
{
result.FullHelp.Properties.Add(new PSNoteProperty("ModuleName", commandInfo.ModuleName));
}
}
return result;
}
/// <summary>
/// ExactMatchHelp implementation for this help provider.
/// </summary>
/// <remarks>
/// ExactMatchHelp is overridden instead of DoExactMatchHelp to make sure
/// all help item retrieval will go through command discovery. Because each
/// help file can contain multiple help items for different commands. Directly
/// retrieve help cache can result in a invalid command to contain valid
/// help item. Forcing each ExactMatchHelp to go through command discovery
/// will make sure helpInfo for invalid command will not be returned.
/// </remarks>
/// <param name="helpRequest">Help request object.</param>
/// <returns></returns>
internal override IEnumerable<HelpInfo> ExactMatchHelp(HelpRequest helpRequest)
{
int countHelpInfosFound = 0;
string target = helpRequest.Target;
// this is for avoiding duplicate result from help output.
var allHelpNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
CommandSearcher searcher = GetCommandSearcherForExactMatch(target, _context);
while (searcher.MoveNext())
{
CommandInfo current = ((IEnumerator<CommandInfo>)searcher).Current;
if (!SessionState.IsVisible(helpRequest.CommandOrigin, current))
{
// this command is not visible to the user (from CommandOrigin) so
// dont show help topic for it.
continue;
}
HelpInfo helpInfo = GetHelpInfo(current, true, false);
string helpName = GetHelpName(current);
if (helpInfo != null && !string.IsNullOrEmpty(helpName))
{
if (helpInfo.ForwardHelpCategory == helpRequest.HelpCategory &&
helpInfo.ForwardTarget.Equals(helpRequest.Target, StringComparison.OrdinalIgnoreCase))
{
throw new PSInvalidOperationException(HelpErrors.CircularDependencyInHelpForwarding);
}
if (allHelpNames.Contains(helpName))
continue;
if (!Match(helpInfo, helpRequest, current))
{
continue;
}
countHelpInfosFound++;
allHelpNames.Add(helpName);
yield return helpInfo;
if ((countHelpInfosFound >= helpRequest.MaxResults) && (helpRequest.MaxResults > 0))
yield break;
}
}
}
private static string GetCmdletAssemblyPath(CmdletInfo cmdletInfo)
{
if (cmdletInfo == null)
return null;
if (cmdletInfo.ImplementingType == null)
return null;
return Path.GetDirectoryName(cmdletInfo.ImplementingType.Assembly.Location);
}
/// <summary>
/// This is a hashtable to track which help files are loaded already.
///
/// This will avoid one help file getting loaded again and again.
/// (Which should not happen unless some commandlet is pointing
/// to a help file that actually doesn't contain the help for it).
/// </summary>
private readonly Hashtable _helpFiles = new Hashtable();
private string GetHelpFile(string helpFile, CmdletInfo cmdletInfo)
{
string helpFileToLoad = helpFile;
// Get the mshsnapinfo object for this cmdlet.
PSSnapInInfo mshSnapInInfo = cmdletInfo.PSSnapIn;
// Search fallback
// 1. If cmdletInfo.HelpFile is a full path to an existing file, directly load that file
// 2. If PSSnapInInfo exists, then always look in the application base of the mshsnapin
// Otherwise,
// Look in the default search path and cmdlet assembly path
Collection<string> searchPaths = new Collection<string>();
if (!File.Exists(helpFileToLoad))
{
helpFileToLoad = Path.GetFileName(helpFileToLoad);
if (mshSnapInInfo != null)
{
Diagnostics.Assert(!string.IsNullOrEmpty(mshSnapInInfo.ApplicationBase),
"Application Base is null or empty.");
// not minishell case..
// we have to search only in the application base for a mshsnapin...
// if you create an absolute path for helpfile, then MUIFileSearcher
// will look only in that path.
searchPaths.Add(HelpUtils.GetUserHomeHelpSearchPath());
searchPaths.Add(mshSnapInInfo.ApplicationBase);
}
else if (cmdletInfo.Module != null && !string.IsNullOrEmpty(cmdletInfo.Module.Path) && !string.IsNullOrEmpty(cmdletInfo.Module.ModuleBase))
{
searchPaths.Add(HelpUtils.GetModuleBaseForUserHelp(cmdletInfo.Module.ModuleBase, cmdletInfo.Module.Name));
searchPaths.Add(cmdletInfo.Module.ModuleBase);
}
else
{
searchPaths.Add(HelpUtils.GetUserHomeHelpSearchPath());
searchPaths.Add(GetDefaultShellSearchPath());
searchPaths.Add(GetCmdletAssemblyPath(cmdletInfo));
}
}
else
{
helpFileToLoad = Path.GetFullPath(helpFileToLoad);
}
string location = MUIFileSearcher.LocateFile(helpFileToLoad, searchPaths);
// let caller take care of getting help info in a different way
// like "get-command -syntax"
if (string.IsNullOrEmpty(location))
{
s_tracer.WriteLine("Unable to load file {0}", helpFileToLoad);
}
return location;
}
/// <summary>
/// Finds a help file associated with the given cmdlet.
/// </summary>
/// <param name="cmdletInfo"></param>
/// <returns></returns>
private string FindHelpFile(CmdletInfo cmdletInfo)
{
if (InternalTestHooks.BypassOnlineHelpRetrieval)
{
// By returning null, we force get-help to generate a metadata driven help object,
// which includes a helpUri that points to the fwlink defined in the cmdlet code.
return null;
}
if (cmdletInfo == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(cmdletInfo));
}
// Get the help file name from the cmdlet metadata
string helpFile = cmdletInfo.HelpFile;
if (string.IsNullOrEmpty(helpFile))
{
if (cmdletInfo.Module != null)
{
if (InitialSessionState.IsEngineModule(cmdletInfo.Module.Name))
{
return System.IO.Path.Combine(cmdletInfo.Module.ModuleBase, CultureInfo.CurrentCulture.Name, s_engineModuleHelpFileCache[cmdletInfo.Module.Name]);
}
}
return helpFile;
}
// This is the path to the help file.
string location = null;
if (helpFile.EndsWith(".ni.dll-Help.xml", StringComparison.OrdinalIgnoreCase))
{
// For PowerShell on OneCore, we ship Ngen binaries. As a result, the name of the assembly now contains '.ni' on it,
// e.g., <AssemblyName>.ni.dll as supposed to <AssemblyName>.dll.
// When cmdlet metadata is generated for the 'HelpFile' field, we use the name assembly and we append '-Help.xml' to it.
// Because of this, if the cmdlet is part of an Ngen assembly, then 'HelpFile' field will be pointing to a help file which does not exist.
// If this is the case, we remove '.ni' from the help file name and try again.
// For example:
// Ngen assembly name: Microsoft.PowerShell.Commands.Management.ni.dll
// Cmdlet metadata 'HelpFile': Microsoft.PowerShell.Commands.Management.ni.dll-Help.xml
// Actual help file name: Microsoft.PowerShell.Commands.Management.dll-Help.xml
// Make sure that the assembly name contains more than '.ni.dll'
string assemblyName = helpFile.Replace(".ni.dll-Help.xml", string.Empty);
if (!string.IsNullOrEmpty(assemblyName))
{
// In the first try, we remove '.ni' from the assembly name and we attempt to find the corresponding help file.
string helpFileName = cmdletInfo.HelpFile.Replace(".ni.dll-Help.xml", ".dll-Help.xml");
location = GetHelpFile(helpFileName, cmdletInfo);
if (string.IsNullOrEmpty(location))
{
// If the help file could not be found, then it is possible that the actual assembly name is something like
// <Name>.ni.dll, e.g., MyAssembly.ni.dll, so let's try to find the original help file in the cmdlet metadata.
location = GetHelpFile(helpFile, cmdletInfo);
}
}
else
{
// the assembly name is actually '.ni.dll'.
location = GetHelpFile(helpFile, cmdletInfo);
}
}
else
{
location = GetHelpFile(helpFile, cmdletInfo);
}
return location;
}
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 (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)
{
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];
if (node.NodeType == XmlNodeType.Element && string.Equals(node.LocalName, "command", StringComparison.OrdinalIgnoreCase))
{
MamlCommandHelpInfo helpInfo = null;
if (isMaml)
{
helpInfo = MamlCommandHelpInfo.Load(node, HelpCategory.Cmdlet);
}
if (helpInfo != null)
{
this.HelpSystem.TraceErrors(helpInfo.Errors);
AddToCommandCache(helpFileIdentifier, helpInfo.Name, helpInfo);
}
}
if (node.NodeType == XmlNodeType.Element && string.Equals(node.Name, "UserDefinedData", StringComparison.OrdinalIgnoreCase))
{
UserDefinedHelpData userDefinedHelpData = UserDefinedHelpData.Load(node);
ProcessUserDefinedHelpData(helpFileIdentifier, userDefinedHelpData);
}
}
}
}
}
/// <summary>
/// Process user defined help data by finding the corresponding helpInfo and inserting
/// necessary helpdata info to command help.
/// </summary>
/// <param name="mshSnapInId">PSSnapIn Name for the current help file.</param>
/// <param name="userDefinedHelpData"></param>
private void ProcessUserDefinedHelpData(string mshSnapInId, UserDefinedHelpData userDefinedHelpData)
{
if (userDefinedHelpData == null)
return;
if (string.IsNullOrEmpty(userDefinedHelpData.Name))
return;
HelpInfo helpInfo = GetFromCommandCache(mshSnapInId, userDefinedHelpData.Name, HelpCategory.Cmdlet);
if (helpInfo == null)
return;
if (!(helpInfo is MamlCommandHelpInfo commandHelpInfo))
return;
commandHelpInfo.AddUserDefinedData(userDefinedHelpData);
return;
}
/// <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="commandName">Name of the command.</param>
/// <param name="helpCategory"></param>
/// <returns>HelpInfo object.</returns>
private HelpInfo GetFromCommandCache(string helpFileIdentifier, string commandName, HelpCategory helpCategory)
{
Debug.Assert(!string.IsNullOrEmpty(commandName), "Cmdlet Name should not be null or empty.");
string key = commandName;
if (!string.IsNullOrEmpty(helpFileIdentifier))
{
key = helpFileIdentifier + "\\" + key;
}
HelpInfo result = GetCache(key);
// Win8: Win8:477680: When Function/Workflow Use External Help, Category Property is "Cmdlet"
if ((result != null) && (result.HelpCategory != helpCategory))
{
MamlCommandHelpInfo original = (MamlCommandHelpInfo)result;
result = original.Copy(helpCategory);
}
return result;
}
/// <summary>
/// Gets the HelpInfo object corresponding to the CommandInfo.
/// </summary>
/// <param name="helpFileIdentifier">Help file identifier (simply full path to help file).</param>
/// <param name="commandInfo"></param>
/// <returns>HelpInfo object.</returns>
private HelpInfo GetFromCommandCache(string helpFileIdentifier, CommandInfo commandInfo)
{
Debug.Assert(commandInfo != null, "commandInfo cannot be null");
HelpInfo result = GetFromCommandCache(helpFileIdentifier, commandInfo.Name, commandInfo.HelpCategory);
if (result == null)
{
// check if the command is prefixed and try retrieving help by removing the prefix
if ((commandInfo.Module != null) && (!string.IsNullOrEmpty(commandInfo.Prefix)))
{
MamlCommandHelpInfo newMamlHelpInfo = GetFromCommandCacheByRemovingPrefix(helpFileIdentifier, commandInfo);
if (newMamlHelpInfo != null)
{
// caching the changed help content under the prefixed name for faster
// retrieval later.
AddToCommandCache(helpFileIdentifier, commandInfo.Name, newMamlHelpInfo);
return newMamlHelpInfo;
}
}
}
return result;
}
/// <summary>
/// Tries to get the help for the Cmdlet from cache.
/// </summary>
/// <param name="cmdletInfo"></param>
/// <returns>
/// HelpInfo object representing help for the command.
/// </returns>
private HelpInfo GetFromCommandCacheOrCmdletInfo(CmdletInfo cmdletInfo)
{
Debug.Assert(cmdletInfo != null, "cmdletInfo cannot be null");
HelpInfo result = GetFromCommandCache(cmdletInfo.ModuleName, cmdletInfo.Name, cmdletInfo.HelpCategory);
if (result == null)
{
// check if the command is prefixed and try retrieving help by removing the prefix
if ((cmdletInfo.Module != null) && (!string.IsNullOrEmpty(cmdletInfo.Prefix)))
{
MamlCommandHelpInfo newMamlHelpInfo = GetFromCommandCacheByRemovingPrefix(cmdletInfo.ModuleName, cmdletInfo);
if (newMamlHelpInfo != null)
{
// Noun exists only for cmdlets...since prefix will change the Noun, updating
// the help content accordingly
if (newMamlHelpInfo.FullHelp.Properties["Details"] != null &&
newMamlHelpInfo.FullHelp.Properties["Details"].Value != null)
{
PSObject commandDetails = PSObject.AsPSObject(newMamlHelpInfo.FullHelp.Properties["Details"].Value);
if (commandDetails.Properties["Noun"] != null)
{
commandDetails.Properties.Remove("Noun");
}
commandDetails.Properties.Add(new PSNoteProperty("Noun", cmdletInfo.Noun));
}
// caching the changed help content under the prefixed name for faster
// retrieval later.
AddToCommandCache(cmdletInfo.ModuleName, cmdletInfo.Name, newMamlHelpInfo);
return newMamlHelpInfo;
}
}
}
return result;
}
/// <summary>
/// Used to retrieve helpinfo by removing the prefix from the noun portion of a command name.
/// Import-Module and Import-PSSession supports changing the name of a command
/// by supplying a custom prefix. In those cases, the help content is stored by using the
/// original command name (without prefix) as the key.
///
/// This method retrieves the help content by suppressing the prefix and then making a copy
/// of the help content + change the name and then returns the copied help content.
/// </summary>
/// <param name="helpIdentifier"></param>
/// <param name="cmdInfo"></param>
/// <returns>
/// Copied help content or null if no help content is found.
/// </returns>
private MamlCommandHelpInfo GetFromCommandCacheByRemovingPrefix(string helpIdentifier, CommandInfo cmdInfo)
{
Dbg.Assert(cmdInfo != null, "cmdInfo cannot be null");
MamlCommandHelpInfo result = null;
MamlCommandHelpInfo originalHelpInfo = GetFromCommandCache(helpIdentifier,
Microsoft.PowerShell.Commands.ModuleCmdletBase.RemovePrefixFromCommandName(cmdInfo.Name, cmdInfo.Prefix),
cmdInfo.HelpCategory) as MamlCommandHelpInfo;
if (originalHelpInfo != null)
{
result = originalHelpInfo.Copy();
// command's name can be changed using -Prefix while importing module.To give better user experience for
// get-help (on par with get-command), it was decided to use the prefixed command name
// for the help content.
if (result.FullHelp.Properties["Name"] != null)
{
result.FullHelp.Properties.Remove("Name");
}
result.FullHelp.Properties.Add(new PSNoteProperty("Name", cmdInfo.Name));
if (result.FullHelp.Properties["Details"] != null &&
result.FullHelp.Properties["Details"].Value != null)
{
// Note we are making a copy of the original instance and updating
// it..This is to protect the help content of the original object.
PSObject commandDetails = PSObject.AsPSObject(
result.FullHelp.Properties["Details"].Value).Copy();
if (commandDetails.Properties["Name"] != null)
{
commandDetails.Properties.Remove("Name");
}
commandDetails.Properties.Add(new PSNoteProperty("Name", cmdInfo.Name));
// Note we made the change to a copy..so assigning the copy back to
// the help content that is returned to the user.
result.FullHelp.Properties["Details"].Value = commandDetails;
}
}
return result;
}
/// <summary>
/// Prepends mshsnapin id to the cmdlet name and adds the result to help cache.
/// </summary>
/// <param name="mshSnapInId">PSSnapIn name that this cmdlet belongs to.</param>
/// <param name="cmdletName">Name of the cmdlet.</param>
/// <param name="helpInfo">Help object for the cmdlet.</param>
private void AddToCommandCache(string mshSnapInId, string cmdletName, MamlCommandHelpInfo helpInfo)
{
Debug.Assert(!string.IsNullOrEmpty(cmdletName), "Cmdlet Name should not be null or empty.");
string key = cmdletName;
// Add snapin qualified type name for this command at the top..
// this will enable customizations of the help object.
helpInfo.FullHelp.TypeNames.Insert(
index: 0,
string.Create(
CultureInfo.InvariantCulture,
$"MamlCommandHelpInfo#{mshSnapInId}#{cmdletName}"));
if (!string.IsNullOrEmpty(mshSnapInId))
{
key = mshSnapInId + "\\" + key;
// Add snapin name to the typenames of this object
helpInfo.FullHelp.TypeNames.Insert(
index: 1,
string.Create(
CultureInfo.InvariantCulture,
$"MamlCommandHelpInfo#{mshSnapInId}"));
}
AddCache(key, 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"></param>
/// <param name="helpItemsNode"></param>
/// <returns></returns>
internal static bool IsMamlHelp(string helpFile, XmlNode helpItemsNode)
{
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;
}
/// <summary>
/// Search help for a specific target.
/// </summary>
/// <param name="helpRequest">Help request object.</param>
/// <param name="searchOnlyContent">
/// If true, searches for pattern in the help content of all cmdlets.
/// Otherwise, searches for pattern in the cmdlet names.
/// </param>
/// <returns></returns>
internal override IEnumerable<HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent)
{
string target = helpRequest.Target;
Collection<string> patternList = new Collection<string>();
// this will be used only when searchOnlyContent == true
WildcardPattern wildCardPattern = null;
// Decorated Search means that original match target is a target without
// wildcard patterns. It come here to because exact match was not found
// and search target will be decorated with wildcard character '*' to
// search again.
bool decoratedSearch = !WildcardPattern.ContainsWildcardCharacters(helpRequest.Target);
if (!searchOnlyContent)
{
if (decoratedSearch)
{
if (target.Contains(StringLiterals.CommandVerbNounSeparator))
{
patternList.Add(target + "*");
}
else
{
patternList.Add("*" + target + "*");
}
}
else
{
patternList.Add(target);
}
}
else
{
// get help for all cmdlets.
patternList.Add("*");
string searchTarget = helpRequest.Target;
if (decoratedSearch)
{
searchTarget = "*" + helpRequest.Target + "*";
}
wildCardPattern = WildcardPattern.Get(searchTarget, WildcardOptions.Compiled | WildcardOptions.IgnoreCase);
}
int countOfHelpInfoObjectsFound = 0;
// this is for avoiding duplicate result from help output.
var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var hiddenCommands = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string pattern in patternList)
{
CommandSearcher searcher = GetCommandSearcherForSearch(pattern, _context);
while (searcher.MoveNext())
{
if (_context.CurrentPipelineStopping)
{
yield break;
}
CommandInfo current = ((IEnumerator<CommandInfo>)searcher).Current;
HelpInfo helpInfo = GetHelpInfo(current, !decoratedSearch, searchOnlyContent);
string helpName = GetHelpName(current);
if (helpInfo != null && !string.IsNullOrEmpty(helpName))
{
if (!SessionState.IsVisible(helpRequest.CommandOrigin, current))
{
// this command is not visible to the user (from CommandOrigin) so
// dont show help topic for it.
hiddenCommands.Add(helpName);
continue;
}
if (set.Contains(helpName))
continue;
// filter out the helpInfo object depending on user request
if (!Match(helpInfo, helpRequest, current))
{
continue;
}
// Search content
if (searchOnlyContent && (!helpInfo.MatchPatternInContent(wildCardPattern)))
{
continue;
}
set.Add(helpName);
countOfHelpInfoObjectsFound++;
yield return helpInfo;
if (countOfHelpInfoObjectsFound >= helpRequest.MaxResults && helpRequest.MaxResults > 0)
yield break;
}
}
if (this.HelpCategory == (HelpCategory.Alias | HelpCategory.Cmdlet))
{
foreach (CommandInfo current in ModuleUtils.GetMatchingCommands(pattern, _context, helpRequest.CommandOrigin))
{
if (_context.CurrentPipelineStopping)
{
yield break;
}
if (!SessionState.IsVisible(helpRequest.CommandOrigin, current))
{
// this command is not visible to the user (from CommandOrigin) so
// dont show help topic for it.
continue;
}
HelpInfo helpInfo = GetHelpInfo(current, !decoratedSearch, searchOnlyContent);
string helpName = GetHelpName(current);
if (helpInfo != null && !string.IsNullOrEmpty(helpName))
{
if (set.Contains(helpName))
continue;
if (hiddenCommands.Contains(helpName))
continue;
// filter out the helpInfo object depending on user request
if (!Match(helpInfo, helpRequest, current))
{
continue;
}
// Search content
if (searchOnlyContent && (!helpInfo.MatchPatternInContent(wildCardPattern)))
{
continue;
}
set.Add(helpName);
countOfHelpInfoObjectsFound++;
yield return helpInfo;
if (countOfHelpInfoObjectsFound >= helpRequest.MaxResults && helpRequest.MaxResults > 0)
yield break;
}
}
}
}
}
/// <summary>
/// Check if a helpInfo object matches the component/role/functionality
/// criteria from helpRequest.
/// </summary>
/// <param name="helpInfo"></param>
/// <param name="helpRequest"></param>
/// <param name="commandInfo"></param>
/// <returns></returns>
private static bool Match(HelpInfo helpInfo, HelpRequest helpRequest, CommandInfo commandInfo)
{
if (helpRequest == null)
return true;
if ((helpRequest.HelpCategory & commandInfo.HelpCategory) == 0)
{
return false;
}
if (helpInfo is not BaseCommandHelpInfo)
return false;
if (!Match(helpInfo.Component, helpRequest.Component))
{
return false;
}
if (!Match(helpInfo.Role, helpRequest.Role))
{
return false;
}
if (!Match(helpInfo.Functionality, helpRequest.Functionality))
{
return false;
}
return true;
}
private static bool Match(string target, string pattern)
{
if (string.IsNullOrEmpty(pattern))
return true;
if (string.IsNullOrEmpty(target))
target = string.Empty;
WildcardPattern matcher = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);
return matcher.IsMatch(target);
}
/// <summary>
/// Checks whether <paramref name="target"/> matches any of the patterns
/// present in <paramref name="patterns"/>
/// </summary>
/// <param name="target">Content to search in.</param>
/// <param name="patterns">String patterns to look for.</param>
/// <returns>
/// true if <paramref name="target"/> contains any of the patterns
/// present in <paramref name="patterns"/>
/// false otherwise.
/// </returns>
private static bool Match(string target, ICollection<string> patterns)
{
// patterns should never be null as shell never accepts
// empty inputs. Keeping this check as a safe measure.
if (patterns == null || patterns.Count == 0)
return true;
foreach (string pattern in patterns)
{
if (Match(target, pattern))
{
// we have a match so return true
return true;
}
}
// We dont have a match so far..so return false
return false;
}
/// <summary>
/// Process helpInfo forwarded over from other providers, specificly AliasHelpProvider.
/// This can return more than 1 helpinfo object.
/// </summary>
/// <param name="helpInfo">HelpInfo that is forwarded over.</param>
/// <param name="helpRequest">Help request object.</param>
/// <returns>The result helpInfo objects after processing.</returns>
internal override IEnumerable<HelpInfo> ProcessForwardedHelp(HelpInfo helpInfo, HelpRequest helpRequest)
{
const HelpCategory categoriesHandled = (HelpCategory.Alias
| HelpCategory.ExternalScript | HelpCategory.Filter | HelpCategory.Function | HelpCategory.ScriptCommand);
if ((helpInfo.HelpCategory & categoriesHandled) != 0)
{
HelpRequest commandHelpRequest = helpRequest.Clone();
commandHelpRequest.Target = helpInfo.ForwardTarget;
commandHelpRequest.CommandOrigin = CommandOrigin.Internal; // a public command can forward help to a private command
// We may know what category to forward to. If so, just set it. If not, look up the
// command and determine it's category. For aliases, we definitely don't know the category
// to forward to, so always do the lookup.
if (helpInfo.ForwardHelpCategory != HelpCategory.None && helpInfo.HelpCategory != HelpCategory.Alias)
{
commandHelpRequest.HelpCategory = helpInfo.ForwardHelpCategory;
}
else
{
try
{
CommandInfo targetCommand = _context.CommandDiscovery.LookupCommandInfo(commandHelpRequest.Target);
commandHelpRequest.HelpCategory = targetCommand.HelpCategory;
}
catch (CommandNotFoundException)
{
// ignore errors for aliases pointing to non-existent commands
}
}
foreach (HelpInfo helpInfoToReturn in ExactMatchHelp(commandHelpRequest))
{
yield return helpInfoToReturn;
}
}
else
{
// command help provider can forward process only an AliasHelpInfo..
// so returning the original help info here.
yield return helpInfo;
}
}
/// <summary>
/// This will reset the help cache. Normally this corresponds to a
/// help culture change.
/// </summary>
internal override void Reset()
{
base.Reset();
_helpFiles.Clear();
}
#endregion
#region Extensions
/// <summary>
/// Gets a command searcher used for ExactMatch help lookup.
/// </summary>
/// <param name="commandName"></param>
/// <param name="context"></param>
/// <returns></returns>
internal virtual CommandSearcher GetCommandSearcherForExactMatch(string commandName, ExecutionContext context)
{
CommandSearcher searcher = new CommandSearcher(
commandName,
SearchResolutionOptions.None,
CommandTypes.Cmdlet,
context);
return searcher;
}
/// <summary>
/// Gets a command searcher used for searching help.
/// </summary>
/// <param name="pattern"></param>
/// <param name="context"></param>
/// <returns></returns>
internal virtual CommandSearcher GetCommandSearcherForSearch(string pattern, ExecutionContext context)
{
CommandSearcher searcher =
new CommandSearcher(
pattern,
SearchResolutionOptions.CommandNameIsPattern,
CommandTypes.Cmdlet,
context);
return searcher;
}
#endregion
#region tracer
[TraceSource("CommandHelpProvider", "CommandHelpProvider")]
private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("CommandHelpProvider", "CommandHelpProvider");
#endregion tracer
}
/// <summary>
/// This is the class to track the user-defined Help Data which is separate from the
/// commandHelp itself.
///
/// Legally, user-defined Help Data should be within the same file as the corresponding
/// commandHelp and it should appear after the commandHelp.
/// </summary>
internal sealed class UserDefinedHelpData
{
private UserDefinedHelpData()
{
}
internal Dictionary<string, string> Properties { get; } = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private string _name = null;
internal string Name
{
get
{
return _name;
}
}
internal static UserDefinedHelpData Load(XmlNode dataNode)
{
if (dataNode == null)
return null;
UserDefinedHelpData userDefinedHelpData = new UserDefinedHelpData();
for (int i = 0; i < dataNode.ChildNodes.Count; i++)
{
XmlNode node = dataNode.ChildNodes[i];
if (node.NodeType == XmlNodeType.Element)
{
userDefinedHelpData.Properties[node.Name] = node.InnerText.Trim();
}
}
string name;
if (!userDefinedHelpData.Properties.TryGetValue("name", out name))
{
return null;
}
userDefinedHelpData._name = name;
if (string.IsNullOrEmpty(userDefinedHelpData.Name))
return null;
return userDefinedHelpData;
}
}
}
|