From 2f96205aded024ea3122a89f2d3c7492eaaff52a Mon Sep 17 00:00:00 2001 From: Sean Wheeler Date: Thu, 10 Jul 2025 16:03:11 -0500 Subject: [PATCH] Reorganize main branch contents --- .../CONTRIBUTING.md | 53 + .../specs/PlatyPS-Design-Notes.md | 147 + .../specs/PowerShellCmdlet.schema.json | 215 ++ .../specs/PowershellCmdletV2.schema.json | 257 ++ .../specs/Schema-Notes.md | 135 + .../specs/alias-prototype.md | 41 + .../specs/platyps_2.0_about_schema.md | 22 + .../specs/platyps_2.0_cmdlets.md | 158 + .../specs/platyps_2.0_update.md | 289 ++ docs/README.md | 35 + docs/platyPS/CONTRIBUTING.md | 138 + {v1 => docs/platyPS}/platyPS.schema.md | 0 .../presentation}/css/impress-demo.css | 0 .../platyPS/presentation}/images/FFFUUU.png | Bin .../presentation}/images/azure-maml.png | Bin .../platyPS/presentation}/images/get-help.png | Bin .../presentation}/images/markdown-github.png | Bin .../platyPS/presentation}/images/markdown.png | Bin .../images/pscmdlethelpeditor.png | Bin .../presentation}/images/psreadline-maml.png | Bin .../platyPS/presentation}/index.html | 0 .../platyPS/presentation}/js/impress.js | 0 v1/.travis.yml | 24 - v1/Markdown.MAML.sln | 36 - v1/appveyor.yml | 63 - v1/build.ps1 | 86 - v1/docs/Get-HelpPreview.md | 111 - v1/docs/Get-MarkdownMetadata.md | 138 - v1/docs/Merge-MarkdownHelp.md | 157 - v1/docs/New-ExternalHelp.md | 241 -- v1/docs/New-ExternalHelpCab.md | 126 - v1/docs/New-MarkdownAboutHelp.md | 111 - v1/docs/New-MarkdownHelp.md | 513 --- v1/docs/New-YamlHelp.md | 153 - v1/docs/Update-MarkdownHelp.md | 256 -- v1/docs/Update-MarkdownHelpModule.md | 263 -- v1/docs/about_platyPS.md | 18 - v1/src/Markdown.MAML/Markdown.MAML.csproj | 15 - .../Markdown.MAML/Model/MAML/MamlCodeBlock.cs | 37 - .../Markdown.MAML/Model/MAML/MamlCommand.cs | 72 - .../Markdown.MAML/Model/MAML/MamlExample.cs | 39 - .../Model/MAML/MamlInputOutput.cs | 34 - v1/src/Markdown.MAML/Model/MAML/MamlLink.cs | 46 - .../Markdown.MAML/Model/MAML/MamlParameter.cs | 109 - v1/src/Markdown.MAML/Model/MAML/MamlSyntax.cs | 22 - .../Model/Markdown/CodeBlockNode.cs | 21 - .../Model/Markdown/DocumentNode.cs | 26 - .../Model/Markdown/HardBreakSpan.cs | 10 - .../Model/Markdown/HeadingNode.cs | 24 - .../Model/Markdown/HyperlinkSpan.cs | 15 - .../Model/Markdown/MarkdownNode.cs | 7 - .../Model/Markdown/MarkdownNodeType.cs | 11 - .../Model/Markdown/ParagraphNode.cs | 23 - .../Model/Markdown/ParagraphSpan.cs | 20 - .../Model/Markdown/SectionBody.cs | 33 - .../Model/Markdown/SectionFormatOption.cs | 18 - .../Model/Markdown/SourceExtent.cs | 87 - .../Markdown.MAML/Model/Markdown/TextNode.cs | 15 - .../Markdown.MAML/Model/Markdown/TextSpan.cs | 27 - .../Markdown.MAML/Model/YAML/YamlCommand.cs | 20 - .../Markdown.MAML/Model/YAML/YamlExample.cs | 10 - .../Model/YAML/YamlInputOutput.cs | 8 - v1/src/Markdown.MAML/Model/YAML/YamlLink.cs | 8 - v1/src/Markdown.MAML/Model/YAML/YamlModule.cs | 7 - .../Markdown.MAML/Model/YAML/YamlParameter.cs | 17 - v1/src/Markdown.MAML/Model/YAML/YamlSyntax.cs | 11 - v1/src/Markdown.MAML/Parser/MarkdownParser.cs | 646 ---- .../Markdown.MAML/Parser/MarkdownPattern.cs | 43 - .../Parser/MarkdownPatternList.cs | 47 - .../Markdown.MAML/Properties/AssemblyInfo.cs | 3 - v1/src/Markdown.MAML/Renderer/MamlRenderer.cs | 234 -- .../Renderer/Markdownv2Renderer.cs | 607 ---- .../Markdown.MAML/Renderer/RenderCleaner.cs | 62 - v1/src/Markdown.MAML/Renderer/TextRenderer.cs | 183 - v1/src/Markdown.MAML/Renderer/YamlRenderer.cs | 97 - .../Resources/MarkdownStrings.Designer.cs | 289 -- .../Resources/MarkdownStrings.resx | 195 -- .../Transformer/HelpSchemaException.cs | 30 - .../Transformer/IModelTransformer.cs | 11 - .../Markdown.MAML/Transformer/MamlComparer.cs | 83 - .../Transformer/MamlModelMerger.cs | 286 -- .../Transformer/MamlMultiModelMerger.cs | 331 -- .../Transformer/ModelTransformerBase.cs | 498 --- .../Transformer/ModelTransformerVersion2.cs | 469 --- v1/src/platyPS/platyPS.Resources.psd1 | 78 - v1/src/platyPS/platyPS.psd1 | 131 - v1/src/platyPS/platyPS.psm1 | 3112 ----------------- v1/templates/aboutTemplate.md | 57 - v1/test/Markdown.MAML.Test/Common.cs | 15 - .../EndToEnd/EndToEndTests.cs | 547 --- .../Markdown.MAML.Test.csproj | 23 - .../Markdown.MAML.Test/Parser/ParserTests.cs | 733 ---- .../Renderer/MamlRendererTests.cs | 242 -- .../Renderer/MarkdownV2RendererTests.cs | 724 ---- .../Renderer/TextRendererTests.cs | 424 --- .../Renderer/YamlRendererTests.cs | 290 -- .../Transformer/MamlModelMergerTests.cs | 228 -- .../Transformer/MamlMultiModelMergerTests.cs | 541 --- .../ParserAndTransformerTestsV2.cs | 1139 ------ v1/test/Pester/FullLoop.Tests.ps1 | 255 -- v1/test/Pester/PlatyPs.Tests.ps1 | 1615 --------- .../Compare-CommandHelp.md | 134 - .../Export-MamlCommandHelp.md | 210 -- .../Export-MarkdownCommandHelp.md | 279 -- .../Export-MarkdownModuleFile.md | 239 -- .../Export-YamlCommandHelp.md | 260 -- .../Export-YamlModuleFile.md | 237 -- .../Import-MamlHelp.md | 124 - .../Import-MarkdownCommandHelp.md | 156 - .../Import-MarkdownModuleFile.md | 138 - .../Import-YamlCommandHelp.md | 177 - .../Import-YamlModuleFile.md | 155 - .../Measure-PlatyPSMarkdown.md | 153 - .../Microsoft.PowerShell.PlatyPS.md | 98 - .../New-CommandHelp.md | 124 - .../New-MarkdownCommandHelp.md | 413 --- .../New-MarkdownModuleFile.md | 332 -- .../Test-MarkdownCommandHelp.md | 177 - .../Update-CommandHelp.md | 177 - .../Update-MarkdownCommandHelp.md | 218 -- .../Update-MarkdownModuleFile.md | 360 -- 121 files changed, 1490 insertions(+), 21517 deletions(-) create mode 100644 docs/Microsoft.PowerShell.PlatyPS/CONTRIBUTING.md create mode 100644 docs/Microsoft.PowerShell.PlatyPS/specs/PlatyPS-Design-Notes.md create mode 100644 docs/Microsoft.PowerShell.PlatyPS/specs/PowerShellCmdlet.schema.json create mode 100644 docs/Microsoft.PowerShell.PlatyPS/specs/PowershellCmdletV2.schema.json create mode 100644 docs/Microsoft.PowerShell.PlatyPS/specs/Schema-Notes.md create mode 100644 docs/Microsoft.PowerShell.PlatyPS/specs/alias-prototype.md create mode 100644 docs/Microsoft.PowerShell.PlatyPS/specs/platyps_2.0_about_schema.md create mode 100644 docs/Microsoft.PowerShell.PlatyPS/specs/platyps_2.0_cmdlets.md create mode 100644 docs/Microsoft.PowerShell.PlatyPS/specs/platyps_2.0_update.md create mode 100644 docs/README.md create mode 100644 docs/platyPS/CONTRIBUTING.md rename {v1 => docs/platyPS}/platyPS.schema.md (100%) rename {presentation => docs/platyPS/presentation}/css/impress-demo.css (100%) rename {presentation => docs/platyPS/presentation}/images/FFFUUU.png (100%) rename {presentation => docs/platyPS/presentation}/images/azure-maml.png (100%) rename {presentation => docs/platyPS/presentation}/images/get-help.png (100%) rename {presentation => docs/platyPS/presentation}/images/markdown-github.png (100%) rename {presentation => docs/platyPS/presentation}/images/markdown.png (100%) rename {presentation => docs/platyPS/presentation}/images/pscmdlethelpeditor.png (100%) rename {presentation => docs/platyPS/presentation}/images/psreadline-maml.png (100%) rename {presentation => docs/platyPS/presentation}/index.html (100%) rename {presentation => docs/platyPS/presentation}/js/impress.js (100%) delete mode 100644 v1/.travis.yml delete mode 100644 v1/Markdown.MAML.sln delete mode 100644 v1/appveyor.yml delete mode 100644 v1/build.ps1 delete mode 100644 v1/docs/Get-HelpPreview.md delete mode 100644 v1/docs/Get-MarkdownMetadata.md delete mode 100644 v1/docs/Merge-MarkdownHelp.md delete mode 100644 v1/docs/New-ExternalHelp.md delete mode 100644 v1/docs/New-ExternalHelpCab.md delete mode 100644 v1/docs/New-MarkdownAboutHelp.md delete mode 100644 v1/docs/New-MarkdownHelp.md delete mode 100644 v1/docs/New-YamlHelp.md delete mode 100644 v1/docs/Update-MarkdownHelp.md delete mode 100644 v1/docs/Update-MarkdownHelpModule.md delete mode 100644 v1/docs/about_platyPS.md delete mode 100644 v1/src/Markdown.MAML/Markdown.MAML.csproj delete mode 100644 v1/src/Markdown.MAML/Model/MAML/MamlCodeBlock.cs delete mode 100644 v1/src/Markdown.MAML/Model/MAML/MamlCommand.cs delete mode 100644 v1/src/Markdown.MAML/Model/MAML/MamlExample.cs delete mode 100644 v1/src/Markdown.MAML/Model/MAML/MamlInputOutput.cs delete mode 100644 v1/src/Markdown.MAML/Model/MAML/MamlLink.cs delete mode 100644 v1/src/Markdown.MAML/Model/MAML/MamlParameter.cs delete mode 100644 v1/src/Markdown.MAML/Model/MAML/MamlSyntax.cs delete mode 100644 v1/src/Markdown.MAML/Model/Markdown/CodeBlockNode.cs delete mode 100644 v1/src/Markdown.MAML/Model/Markdown/DocumentNode.cs delete mode 100644 v1/src/Markdown.MAML/Model/Markdown/HardBreakSpan.cs delete mode 100644 v1/src/Markdown.MAML/Model/Markdown/HeadingNode.cs delete mode 100644 v1/src/Markdown.MAML/Model/Markdown/HyperlinkSpan.cs delete mode 100644 v1/src/Markdown.MAML/Model/Markdown/MarkdownNode.cs delete mode 100644 v1/src/Markdown.MAML/Model/Markdown/MarkdownNodeType.cs delete mode 100644 v1/src/Markdown.MAML/Model/Markdown/ParagraphNode.cs delete mode 100644 v1/src/Markdown.MAML/Model/Markdown/ParagraphSpan.cs delete mode 100644 v1/src/Markdown.MAML/Model/Markdown/SectionBody.cs delete mode 100644 v1/src/Markdown.MAML/Model/Markdown/SectionFormatOption.cs delete mode 100644 v1/src/Markdown.MAML/Model/Markdown/SourceExtent.cs delete mode 100644 v1/src/Markdown.MAML/Model/Markdown/TextNode.cs delete mode 100644 v1/src/Markdown.MAML/Model/Markdown/TextSpan.cs delete mode 100644 v1/src/Markdown.MAML/Model/YAML/YamlCommand.cs delete mode 100644 v1/src/Markdown.MAML/Model/YAML/YamlExample.cs delete mode 100644 v1/src/Markdown.MAML/Model/YAML/YamlInputOutput.cs delete mode 100644 v1/src/Markdown.MAML/Model/YAML/YamlLink.cs delete mode 100644 v1/src/Markdown.MAML/Model/YAML/YamlModule.cs delete mode 100644 v1/src/Markdown.MAML/Model/YAML/YamlParameter.cs delete mode 100644 v1/src/Markdown.MAML/Model/YAML/YamlSyntax.cs delete mode 100644 v1/src/Markdown.MAML/Parser/MarkdownParser.cs delete mode 100644 v1/src/Markdown.MAML/Parser/MarkdownPattern.cs delete mode 100644 v1/src/Markdown.MAML/Parser/MarkdownPatternList.cs delete mode 100644 v1/src/Markdown.MAML/Properties/AssemblyInfo.cs delete mode 100644 v1/src/Markdown.MAML/Renderer/MamlRenderer.cs delete mode 100644 v1/src/Markdown.MAML/Renderer/Markdownv2Renderer.cs delete mode 100644 v1/src/Markdown.MAML/Renderer/RenderCleaner.cs delete mode 100644 v1/src/Markdown.MAML/Renderer/TextRenderer.cs delete mode 100644 v1/src/Markdown.MAML/Renderer/YamlRenderer.cs delete mode 100644 v1/src/Markdown.MAML/Resources/MarkdownStrings.Designer.cs delete mode 100644 v1/src/Markdown.MAML/Resources/MarkdownStrings.resx delete mode 100644 v1/src/Markdown.MAML/Transformer/HelpSchemaException.cs delete mode 100644 v1/src/Markdown.MAML/Transformer/IModelTransformer.cs delete mode 100644 v1/src/Markdown.MAML/Transformer/MamlComparer.cs delete mode 100644 v1/src/Markdown.MAML/Transformer/MamlModelMerger.cs delete mode 100644 v1/src/Markdown.MAML/Transformer/MamlMultiModelMerger.cs delete mode 100644 v1/src/Markdown.MAML/Transformer/ModelTransformerBase.cs delete mode 100644 v1/src/Markdown.MAML/Transformer/ModelTransformerVersion2.cs delete mode 100644 v1/src/platyPS/platyPS.Resources.psd1 delete mode 100644 v1/src/platyPS/platyPS.psd1 delete mode 100644 v1/src/platyPS/platyPS.psm1 delete mode 100644 v1/templates/aboutTemplate.md delete mode 100644 v1/test/Markdown.MAML.Test/Common.cs delete mode 100644 v1/test/Markdown.MAML.Test/EndToEnd/EndToEndTests.cs delete mode 100644 v1/test/Markdown.MAML.Test/Markdown.MAML.Test.csproj delete mode 100644 v1/test/Markdown.MAML.Test/Parser/ParserTests.cs delete mode 100644 v1/test/Markdown.MAML.Test/Renderer/MamlRendererTests.cs delete mode 100644 v1/test/Markdown.MAML.Test/Renderer/MarkdownV2RendererTests.cs delete mode 100644 v1/test/Markdown.MAML.Test/Renderer/TextRendererTests.cs delete mode 100644 v1/test/Markdown.MAML.Test/Renderer/YamlRendererTests.cs delete mode 100644 v1/test/Markdown.MAML.Test/Transformer/MamlModelMergerTests.cs delete mode 100644 v1/test/Markdown.MAML.Test/Transformer/MamlMultiModelMergerTests.cs delete mode 100644 v1/test/Markdown.MAML.Test/Transformer/ParserAndTransformerTestsV2.cs delete mode 100644 v1/test/Pester/FullLoop.Tests.ps1 delete mode 100644 v1/test/Pester/PlatyPs.Tests.ps1 delete mode 100644 v2docs/Microsoft.PowerShell.PlatyPS/Compare-CommandHelp.md delete mode 100644 v2docs/Microsoft.PowerShell.PlatyPS/Export-MamlCommandHelp.md delete mode 100644 v2docs/Microsoft.PowerShell.PlatyPS/Export-MarkdownCommandHelp.md delete mode 100644 v2docs/Microsoft.PowerShell.PlatyPS/Export-MarkdownModuleFile.md delete mode 100644 v2docs/Microsoft.PowerShell.PlatyPS/Export-YamlCommandHelp.md delete mode 100644 v2docs/Microsoft.PowerShell.PlatyPS/Export-YamlModuleFile.md delete mode 100644 v2docs/Microsoft.PowerShell.PlatyPS/Import-MamlHelp.md delete mode 100644 v2docs/Microsoft.PowerShell.PlatyPS/Import-MarkdownCommandHelp.md delete mode 100644 v2docs/Microsoft.PowerShell.PlatyPS/Import-MarkdownModuleFile.md delete mode 100644 v2docs/Microsoft.PowerShell.PlatyPS/Import-YamlCommandHelp.md delete mode 100644 v2docs/Microsoft.PowerShell.PlatyPS/Import-YamlModuleFile.md delete mode 100644 v2docs/Microsoft.PowerShell.PlatyPS/Measure-PlatyPSMarkdown.md delete mode 100644 v2docs/Microsoft.PowerShell.PlatyPS/Microsoft.PowerShell.PlatyPS.md delete mode 100644 v2docs/Microsoft.PowerShell.PlatyPS/New-CommandHelp.md delete mode 100644 v2docs/Microsoft.PowerShell.PlatyPS/New-MarkdownCommandHelp.md delete mode 100644 v2docs/Microsoft.PowerShell.PlatyPS/New-MarkdownModuleFile.md delete mode 100644 v2docs/Microsoft.PowerShell.PlatyPS/Test-MarkdownCommandHelp.md delete mode 100644 v2docs/Microsoft.PowerShell.PlatyPS/Update-CommandHelp.md delete mode 100644 v2docs/Microsoft.PowerShell.PlatyPS/Update-MarkdownCommandHelp.md delete mode 100644 v2docs/Microsoft.PowerShell.PlatyPS/Update-MarkdownModuleFile.md diff --git a/docs/Microsoft.PowerShell.PlatyPS/CONTRIBUTING.md b/docs/Microsoft.PowerShell.PlatyPS/CONTRIBUTING.md new file mode 100644 index 00000000..0e9a5bee --- /dev/null +++ b/docs/Microsoft.PowerShell.PlatyPS/CONTRIBUTING.md @@ -0,0 +1,53 @@ +# Contributing to platyPS + +## Get the code + +``` +git clone https://github.com/PowerShell/platyPS +``` + +## Understand code layout + +TBD + +## Build + +To build the whole project, use the `build.ps1` helper script. It depends on the +[dotnet cli](https://docs.microsoft.com/en-us/dotnet/core/tools/) build tool. + +On Windows you would also need to +[install full dotnet framework](https://docs.microsoft.com/en-us/dotnet/framework/install/guide-for-developers) +if it's not installed already. + +```powershell +.\build.ps1 +``` + +As part of the build, platyPS generates help for itself. The output of the build is placed in +`out\Microsoft.PowerShell.PlatyPS`. + +`build.ps1` also imports the module from `out\platyPS` and generates help itself. + +> [!NOTE] +> If you changed C# code, `build.ps1` will try to overwrite a DLL in use. You will then need to +> re-open your PowerShell session. If you know a better workflow, please suggest it in the Issues. + +## Tests + +Each part of the project has a test set: + +- The C# part has xUnit tests. +- The PowerShell part has [Pester](https://github.com/pester/Pester) tests. You can run them with + `Invoke-Pester`. + +> [!NOTE] +> Pester tests always force-import the module from the output location of `.\build.ps1`. + +## Schema + +If you have ideas or concerns about the Markdown schema, feel free to open a GitHub Issue to discuss +it. + +## Repo structure + +TBD diff --git a/docs/Microsoft.PowerShell.PlatyPS/specs/PlatyPS-Design-Notes.md b/docs/Microsoft.PowerShell.PlatyPS/specs/PlatyPS-Design-Notes.md new file mode 100644 index 00000000..4c0cc2ce --- /dev/null +++ b/docs/Microsoft.PowerShell.PlatyPS/specs/PlatyPS-Design-Notes.md @@ -0,0 +1,147 @@ +--- +ms.date: 10/22/2024 +--- +# Microsoft.PowerShell.PlatyPS design notes + +## Design notes + +### Features/Functionality + +- When PlatyPS writes file output, it should create folder structure of module-named folders + containing cmdlet markdown for the cmdlets in those modules +- PlatyPS should populate the markdown with all the facts that it can reasonably gather about the + command: + - Name + - Syntax of all parameter sets + - Parameter names and metadata (type, all attributes, etc. arranged by parameter set) + - Common parameters (if supported) + - Input types - types that can be piped to the command + - Output types - as defined by the cmdlet attributes +- PlatyPS should insert placeholder text for all content that must be provided by the author + +### Module notes + +- Total rewrite in C# to improve performance, object model, and extensibility + - Cmdlets are focused on the object model and provide a single purpose + - Chain cmdlets in a pipeline to perform complex operations + - Workflow style cmdlets will be script-based to improve usability for authors + - Script-based provide readable code model that allows end-users to customize their own + workflows as needed + - Workflows are easier to code in script rather than in C# +- Total breaking change from previous versions +- New module name - Microsoft.PowerShell.PlatyPS + - Allows you to install side-by-side with previous versions + - No common cmdlet names between modules + - No intent to provide proxies for old cmdlets +- Cmdlet names better reflect what they do + - Import-SomeFormat + - Export-SomeFormat +- New markdown parsing and rendering powered by markdig +- Module provides Yaml output to be used by the Learn reference pipeline +- Object model is the heart of the new module + - Establishes a common object model for cmdlets and module files + - Markdown is the source of truth for the documentation + - Cmdlets import the markdown in the the CommandHelp object model + - CommandHelp objects can be exported to Markdown, Yaml, or MAML + - CommandHelp objects can be imported from Markdown, Yaml, or MAML + - Conversion to/from MAML is lower fidelity other formats - results in loss of data and accuracy + of the documentation + +### Markdown notes + +- Markdown is the source of truth for the documentation +- Markdown has a strict H2/H3 structure + - You can't add headers or reorder them + - Not all H2/H3 sections require content. The H2/H3 line is required, but the content is optional. + This is done to ensure that the markdown structure is consistent with the object model. +- Metadata names have been changed to match PowerShell property names and common terminology. + - This causes less confusion for authors and makes it easier to troubleshoot validation and + rendering issues +- Import command can read old (0.14) format or new format and converts Markdown into CommandHelp + object +- Export commands convert CommandHelp object into other formats + - Export to markdown command can writes new markdown format + - Export to Yaml is used by the Learn reference pipeline and reflects the new object model + - Export to MAML is lower fidelity and results in loss of data and accuracy of the documentation + due to limitation in Get-Help and the MAML specification +- The Yaml frontmatter is used to store metadata that is not part of the markdown content + - The object model has a set of required key/value pairs + - The `document type` and `PlatyPS schema version` keys are inviolate (cannot be changed) + - You can add custom metadata to the frontmatter + - Any key/value pairs not managed by PlatyPS are passed through unaltered + +### Authoring process + +- Authoring is always a manual process requiring human intervention +- PlatyPS helps automate the process and provides a consistent structure for the documentation but + can't fill in descriptions, examples, or related links + - PlatyPS inserts placeholder text to show you where to add content +- Authors must review and edit the markdown files to ensure that the content is accurate for every + authoring step + - Creating new markdown for new modules/commands + - Migrating existing markdown to the new format + - Updating existing markdown based on new versions of modules/commands + +### Converting to/from other formats + +- Markdown is the source of truth for the documentation +- Converting from the old Markdown format to the new format is a one-way process + - The new format has more structure and metadata than the old format + - The new format is more consistent and easier to validate + - The old format does not reflect all of the correct facts about parameters + - Converting from the old to the new format does not improve the accuracy of the parameter + metadata; you must run the update process +- The update process requires that the commands/modules be available in the current session so + that the complete parameter metadata can be discovered +- Converting to Yaml + - There is no loss of fidelity when converting from the Markdown to Yaml (or vice versa) + - The Yaml is just a serialization of the CommandHelp object model + - All properties are preserved even if the value is null + - Rendering to HTML should handle null values gracefully (e.g. conditional formatting to omit null + values) +- Converting to/from MAML + - There is a loss of fidelity when converting to MAML due to limitations in the MAML specification + and Get-Help cmdlet +- Importing from MAML is supported as a method of last resort. + +## Frontmatter + +| FileType | v1 Key | v1 Status | v2 key | v2 Status | +|----------|--------------------|-----------------------------------------------------|------------------------|----------------------------------------------------| +| cmdlet | | n/a | document type | Required | +| cmdlet | external help file | Required - unique to cmdlet | external help file | Required | +| cmdlet | online version | Key required, value can be null - unique to cmdlet | HelpUri | Key required, value can be null - unique to cmdlet | +| cmdlet | Locale | Required | Locale | Required | +| cmdlet | Module Name | Key required, value can be null | Module Name | Key required, value can be null | +| cmdlet | ms.date | Optional | ms.date | Optional | +| cmdlet | schema | Required | PlatyPS schema version | Required | +| cmdlet | title | Required | title | Required | +| cmdlet | | n/a | aliases | Optional | +| module | | n/a | document type | Required | +| module | Help Version | Key required, value can be null - unique to module | Help Version | Key required, value can be null - unique to module | +| module | Download Help Link | Key required, value can be null - unique to module | HelpInfoUri | Key required, value can be null - unique to module | +| module | Locale | Required | Locale | Required | +| module | Module Guid | Required - unique to module | Module Guid | Required - unique to module | +| module | Module Name | Required | Module Name | Required | +| module | ms.date | Optional | ms.date | Optional | +| module | schema | Required | PlatyPS schema version | Required | +| module | title | Required | title | Required | + +## Scenarios to support OPS + +1. Workflow script to convert all markdown files to YAML in a folder +1. Workflow script for CabGen +1. Make rendering decisions for HTML presentation + +These items to be done by Sean and Jason working with DanniX and team. + +## Future ideas + +- Create a method to convert CommandHelp object to the Get-Help object model + - This could be an easy way to ship markdown instead of MAML for downlevel systems that don't have + or cant support Help v2. +- Add commands to stream conversion to Markdown to support Markdown rendering in the console (e.g. + pipe to `glow.exe`) +- Create workflow convenience scripts to include in module +- Compare-MarkdownCommandHelp - can't compare module files + diff --git a/docs/Microsoft.PowerShell.PlatyPS/specs/PowerShellCmdlet.schema.json b/docs/Microsoft.PowerShell.PlatyPS/specs/PowerShellCmdlet.schema.json new file mode 100644 index 00000000..8636f27e --- /dev/null +++ b/docs/Microsoft.PowerShell.PlatyPS/specs/PowerShellCmdlet.schema.json @@ -0,0 +1,215 @@ +{ + "title": "PowershellCmdlet", + "$schema": "https://dotnet.github.io/docfx/schemas/v1.0/schema.json#", + "version": "1.0.0", + "description": "The schema for powershell cmdlet page", + "id": "https://static.docs.com/ui/latest/schemas/PowershellCmdlet.schema.json", + "type": "object", + "additionalProperties": false, + "required": ["name", "module", "uid"], + "renderType": "content", + "archivable": false, + "properties": { + "applicable": { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + "description": { + "type": "string", + "contentType": "markdown", + "tags": ["localizable"] + }, + "examples": { + "items": { + "additionalProperties": false, + "required": ["title", "summary", "description"], + "properties": { + "title": { + "type": "string", + "tags": ["localizable"] + }, + "summary": { + "type": "string", + "contentType": "markdown", + "tags": ["localizable"] + }, + "code": { + "type": "string" + }, + "description": { + "type": "string", + "contentType": "markdown", + "tags": ["localizable"] + } + }, + "type": "object" + }, + "minItems": 1, + "type": "array" + }, + "inputs": { + "items": { + "additionalProperties": false, + "required": ["name", "description"], + "properties": { + "name": { + "type": "string", + "contentType": "markdown" + }, + "description": { + "type": "string", + "contentType": "markdown", + "tags": ["localizable"] + } + }, + "type": "object" + }, + "minItems": 1, + "type": "array" + }, + "links": { + "items": { + "additionalProperties": false, + "required": ["href", "text"], + "properties": { + "href": { + "type": "string", + "contentType": "href" + }, + "text": { + "type": "string", + "tags": ["localizable"] + } + }, + "type": "object" + }, + "minItems": 1, + "type": "array" + }, + "metadata": { + "properties": { + "description": { + "type": "string", + "tags": ["localizable"] + }, + "title": { + "type": "string", + "tags": ["localizable"] + } + }, + "type": "object" + }, + "module": { + "type": "string", + "contentType": "xref" + }, + "name": { + "type": "string" + }, + "notes": { + "type": "string", + "contentType": "markdown", + "tags": ["localizable"] + }, + "outputs": { + "items": { + "additionalProperties": false, + "required": ["name", "description"], + "properties": { + "name": { + "type": "string", + "contentType": "markdown" + }, + "description": { + "type": "string", + "contentType": "markdown", + "tags": ["localizable"] + } + }, + "type": "object" + }, + "minItems": 1, + "type": "array" + }, + "parameters": { + "items": { + "additionalProperties": false, + "required": ["name", "description", "type", "position"], + "properties": { + "name": { + "type": "string" + }, + "summary": { + "type": "string", + "contentType": "markdown", + "tags": ["localizable"] + }, + "description": { + "type": "string", + "contentType": "markdown", + "tags": ["localizable"] + }, + "isRequired": { + "type": "boolean" + }, + "applicable": { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + "type": { + "type": "string", + "contentType": "markdown" + }, + "aliases": { + "type": "string" + }, + "parameterValueGroup": { + "type": "string" + }, + "position": { + "type": "string" + }, + "defaultValue": { + "type": "string" + }, + "pipelineInput": { + "type": "boolean" + }, + "acceptWildcardCharacters": { + "type": "boolean" + }, + "valueFrom": { + "type": "string" + } + }, + "type": "object" + }, + "minItems": 1, + "type": "array" + }, + "summary": { + "type": "string", + "contentType": "markdown", + "tags": ["localizable"] + }, + "syntaxes": { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + "uid": { + "type": "string", + "contentType": "uid" + } + }, + "metadata": "/metadata", + "xrefProperties": ["name", "summary"] +} diff --git a/docs/Microsoft.PowerShell.PlatyPS/specs/PowershellCmdletV2.schema.json b/docs/Microsoft.PowerShell.PlatyPS/specs/PowershellCmdletV2.schema.json new file mode 100644 index 00000000..2e9e70c1 --- /dev/null +++ b/docs/Microsoft.PowerShell.PlatyPS/specs/PowershellCmdletV2.schema.json @@ -0,0 +1,257 @@ +{ + "title": "PowershellCmdletV2", + "$schema": "https://dotnet.github.io/docfx/schemas/v1.0/schema.json#", + "version": "1.0.0", + "description": "The schema for powershell cmdlet page - version 2", + "id": "https://static.docs.com/ui/latest/schemas/PowershellCmdletV2.schema.json", + "type": "object", + "additionalProperties": false, + "required": ["name", "module", "uid"], // tend to only keep necessary items for OPS, may validate the rest through Docs.Validation service by contacting Megan Bradley + "renderType": "content", + "archivable": false, + "properties": { + "aliases": { + "type": "string", + "contentType": "markdown", + "tags": ["localizable"] + }, + "applicable": { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + "description": { + "type": "string", + "contentType": "markdown", + "tags": ["localizable"] + }, + "examples": { // Remove something. For fixing the mixture of code and output, PlatyPS issue #576. This change should take effect along with or after integrating PlatyPS v2 New-YamlHelp, because current MAML2YAML generates summary from content. + "items": { + "additionalProperties": false, + "required": ["title", "description"], + "properties": { + "title": { + "type": "string", + "tags": ["localizable"] + }, + "description": { + "type": "string", + "contentType": "markdown", + "tags": ["localizable"] + } + }, + "type": "object" + }, + "minItems": 1, + "type": "array" + }, + "inputs": { + "items": { + "additionalProperties": false, + "required": ["name", "description"], + "properties": { + "name": { + "type": "string", + "contentType": "markdown" + }, + "description": { + "type": "string", + "contentType": "markdown", + "tags": ["localizable"] + } + }, + "type": "object" + }, + "minItems": 1, + "type": "array" + }, + "links": { + "items": { + "additionalProperties": false, + "required": ["href", "text"], + "properties": { + "href": { + "type": "string", + "contentType": "href" + }, + "text": { + "type": "string", + "tags": ["localizable"] + } + }, + "type": "object" + }, + "minItems": 1, + "type": "array" + }, + "metadata": { + "properties": { + "description": { + "type": "string", + "tags": ["localizable"] + }, + "title": { + "type": "string", + "tags": ["localizable"] + } + }, + "type": "object" + }, + "module": { + "type": "string", + "contentType": "xref" + }, + "name": { + "type": "string" + }, + "notes": { + "type": "string", + "contentType": "markdown", + "tags": ["localizable"] + }, + "outputs": { + "items": { + "additionalProperties": false, + "required": ["name", "description"], + "properties": { + "name": { + "type": "string", + "contentType": "markdown" + }, + "description": { + "type": "string", + "contentType": "markdown", + "tags": ["localizable"] + } + }, + "type": "object" + }, + "minItems": 1, + "type": "array" + }, + "parameters": { // Add & modify something. This change should take effect along with or after integrating PlatyPS v2 New-YamlHelp, because current MAML2YAML does not transform commonParameters into yaml from markdown. + "properties": { + "cmdletParameters": { // naming pending? use only a single word as the name if possible + "items": { + "additionalProperties": false, + "required": ["name", "description", "type", "parameterSet"], + "properties": { + "name": { + "type": "string" + }, + "description": { + "type": "string", + "contentType": "markdown", + "tags": ["localizable"] + }, + "type": { + "type": "string", + "contentType": "markdown" + }, + "parameterSet" : { + "items": { + "type": "array", + "minItems": 1, + "additionalProperties": false, + "required": [ "name" ], + "properties": { + "name": { + "type": "string" + }, + "position": { + "type": "string" + }, + "valueByPipeline": { + "type": "boolean" + }, + "valueByPipelineByPropertyName": { + "type": "boolean" + }, + "valueFromRemainingArguments": { + "type": "boolean" + }, + "isRequired": { // mandatory + "type": "boolean" + } + } + } + }, + "applicable": { // ???? + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + "aliases": { + "type": "array", + "minItems": 1, + "items": { + "type": "string" + } + }, + "isDynamic": { + "type": "boolean" + }, + "allowedValues": { // parameterValueGroup + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + "defaultValue": { + "type": "string" + }, + "acceptWildcardCharacters": { + "type": "boolean" + }, + "confirmImpact": { + "type": "string" + } + }, + "type": "object" + }, + "minItems": 1, + "type": "array" + }, + "commonParameters": { // This implies has cmdlet binding + "type": "string", + "contentType": "markdown", + "tags": ["localizable"] + } + }, + "type": "object" + }, + "summary": { + "type": "string", + "contentType": "markdown", + "tags": ["localizable"] + }, + "syntaxes": { // Change type and add properties. This change should take effect along with or after integrating PlatyPS v2 New-YamlHelp, because current MAML2YAML generates text for this part. + "items": { + "additionalProperties": false, + "required": ["parameterSetName", "syntax"], + "properties": { + "parameterSetName": { + "type": "string" + }, + "syntax": { // naming pending? use only a single word as the name if possible + "type": "string" + } + }, + "type": "object" + }, + "minItems": 1, + "type": "array" + }, + "uid": { + "type": "string", + "contentType": "uid" + } + }, + "metadata": "/metadata", + "xrefProperties": ["name", "summary"] +} diff --git a/docs/Microsoft.PowerShell.PlatyPS/specs/Schema-Notes.md b/docs/Microsoft.PowerShell.PlatyPS/specs/Schema-Notes.md new file mode 100644 index 00000000..2c279340 --- /dev/null +++ b/docs/Microsoft.PowerShell.PlatyPS/specs/Schema-Notes.md @@ -0,0 +1,135 @@ +This the current layout of the markdown for a Cmdlet with notes: + +YAML Frontmatter + +- Need to not error on PlatyPS required keys (external help file, Locale, Module Name, ms.date, + online version, schema, title) +- What should we do about description? - currently copied by OPS from Description below +- Mapping to existing JSON schema: properties/metadata + +Title + +- Type: H1 +- Required: Y +- Count: 1 +- Mapping to existing JSON schema: properties/name + +Synopsis + +- Type: H2 +- Required: Y +- Count: 1 +- Mapping to existing JSON schema: properties/summary + +Syntax + +- Type: H2 +- Required: Y +- Count: 1 +- Required: No changes +- Mapping to existing JSON schema: properties/syntaxes +- Notes: Contains 1 or more of the following: + - Parameter Set name + - Type: H3 + - Required: Y + - Count: 1-N + - Parameter Sets - should be sorted starting with Default, then by Alpha +- Parameters (in syntax block) + - Syntax block + - What format do you want? - Currently MAML2Yaml is using the strings from the code block instead + of a Yaml data model. Prefer the string model. + +Description + +- Type: H2 +- Required: Y +- Count: 1 +- Mapping to existing JSON schema: properties/description +- Allow any markdown content type except Headers + +Examples + +- Type: H2 +- Required: Y +- Count: 1 +- Mapping to existing JSON schema: properties/examples +- Notes: Contains 1 or more of the following + - Example + - Type: H3 + - Required: Y + - Count: 1-N + - Should require one code block at minimum per example + - Should allow a mix of markdown code blocks and paragraphs in any order + +Parameters + +- Type: H2 +- Required: Y +- Count: 1 +- Mapping to existing JSON schema: properties/parameters +- Parameters should be sorted Alphabetically followed by `-Confirm` and `-WhatIf` (when included). + PlatyPS has the `-AlphabeticParamsOrder` parameter that produces this order. +- Notes: Contains 1 or more of the following + - Parameter + - Type: H3 + - Required: Y + - Count: 1-N + - Required: Yaml block should include: + - Parameter Set Name + - Position can be different per parameter set + - Add **AcceptedValues** - Should display enumerated values of parameter (like ValidateSet) + - maps to properties/parameters/parameterValueGroup? + - Add **ConfirmImpact** - Impact severity should be reflected and displayed to inform defaults + for `-Confirm` + - what is **valueFrom** in JSON schema? + - **pipelineInput** is currently a boolean. The value can be different per parameter set to + the type needs to be a string + +Common Parameters + +- Type: H3 +- Required: Y +- Count: 1 +- Notes: + - this is missing from the schema - need to define it + - The content should be the markdown description provided in the file + +Inputs + +- Type: H2 +- Required: Y +- Count: 1 +- Mapping to existing JSON schema: properties/inputs +- Notes: Contains 0 or more of the following: + - Input type + - Type: H3 + - Required: N + - Count: 0-N + +Outputs + +- Type: H2 +- Required: Y +- Count: 1 +- Mapping to existing JSON schema: properties/outputs +- Notes: Contains 0 or more of the following: + - Output type + - Type: H3 + - Required: N + - Count: 0-N + +Notes + +- Type: H2 +- Required: N +- Mapping to existing JSON schema: properties/notes +- Count: 1 header with 0 or more markdown elements (excluding header types) + +Related links + +- Type: H3 +- Required: Y +- Count: 1 +- Mapping to existing JSON schema: properties/links +- Link list should use a bullet list +- Should support markdown paragraphs not just links diff --git a/docs/Microsoft.PowerShell.PlatyPS/specs/alias-prototype.md b/docs/Microsoft.PowerShell.PlatyPS/specs/alias-prototype.md new file mode 100644 index 00000000..9da66a77 --- /dev/null +++ b/docs/Microsoft.PowerShell.PlatyPS/specs/alias-prototype.md @@ -0,0 +1,41 @@ +--- +external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml +Locale: en-US +Module Name: Microsoft.PowerShell.Management +ms.date: 12/05/2023 +online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.management/get-childitem?view=powershell-7.2&WT.mc_id=ps-gethelp +schema: 2.0.0 +title: Get-ChildItem +alias: [dir, gci, ls] +--- +# Get-ChildItem + +## SYNOPSIS + +Gets the items and child items in one or more specified locations. + +## ALIASES + +PowerShell includes the following aliases for `Get-ChildItem`: + +- All platforms: `dir`, `gci` +- Windows: `ls` + +## SYNTAX + +### Items (Default) + +``` +Get-ChildItem [[-Path] ] [[-Filter] ] [-Include ] [-Exclude ] + [-Recurse] [-Depth ] [-Force] [-Name] [-Attributes ] + [-FollowSymlink] [-Directory] [-File] [-Hidden] [-ReadOnly] [-System] [] +``` + +### LiteralItems + +``` +Get-ChildItem [[-Filter] ] -LiteralPath [-Include ] + [-Exclude ] [-Recurse] [-Depth ] [-Force] [-Name] + [-Attributes ] [-FollowSymlink] [-Directory] [-File] [-Hidden] + [-ReadOnly] [-System] [] +``` diff --git a/docs/Microsoft.PowerShell.PlatyPS/specs/platyps_2.0_about_schema.md b/docs/Microsoft.PowerShell.PlatyPS/specs/platyps_2.0_about_schema.md new file mode 100644 index 00000000..6d16b18e --- /dev/null +++ b/docs/Microsoft.PowerShell.PlatyPS/specs/platyps_2.0_about_schema.md @@ -0,0 +1,22 @@ +# Schema for About_ files + +The following sections outline schema changes for the About_ file. + +| Heading | Level | Required? | Count | Description | +| ----------------- | ----- | --------- | ----- | ------------------------------------------------------------------------------------------------------------------------- | +| Title | H1 | Y | 1 | - Title should be Sentence Case - About Topic
- Title meta data 'about_' should match the file basename | +| Short Description | H2 | Y | 1 | - Should be Sentence Case | +| Long Description | H2 | Y | 1 | - Should be Sentence case
- Should allow multiple Long description subtopics
- Should support subtopics at H3 or H2 | +| See Also | H2 | Y | 1 | - This is required but may be empty | + +General notes + +- Should be rendered as plain text compatible with `Get-Help` +- `Get-Help` bug:Synopsis +- [Get-Help bug][05] +- Add switch to provide Cabs or Zips. Default: cabs +- Add switch to include markdown Default: off +- About_ schema does not say anything about line wrapping etc. + - If left as text files, then wrap at 80 columns. + - But if converted to schema-based line limit isn't a problem (for the future). Still a problem + for previous versions. diff --git a/docs/Microsoft.PowerShell.PlatyPS/specs/platyps_2.0_cmdlets.md b/docs/Microsoft.PowerShell.PlatyPS/specs/platyps_2.0_cmdlets.md new file mode 100644 index 00000000..33aeb0d2 --- /dev/null +++ b/docs/Microsoft.PowerShell.PlatyPS/specs/platyps_2.0_cmdlets.md @@ -0,0 +1,158 @@ +## PlatyPS Cmdlets and Parameters + +PlatyPS includes a set of cmdlets with parameters. + +The following section is a review of the cmdlets for changes to the parameters and their defaults. +We need to decide to what cmdlets and features to keep. We should make a list breaking changes for +documentation. + +In case of breaking changes, do we need a legacy mode? + +- We don't know until we see what all the breaking changes are +- If we make changes that require changes to Get-Help we will need something that targets a older + versions PowerShell. + +#### Get-HelpPreview + +| ParamName | DefaultValue | Description | +| ---------------------- | ------------ | ------------------------------------------------------------------------------------------ | +| Path | None | Specifies an array of paths of MAML external help files | +| ConvertNotesToList | False | Indicates that this cmldet formats multiple paragraph items in the NOTES section as single | +| ConvertDoubleDashLists | False | Indicates that this cmldet converts double-hyphen list bullets into single-hyphen bullets | + +#### Get-MarkdownMetadata + +| ParamName | DefaultValue | Description | +| --------- | ------------ | -------------------------------------------------------- | +| Path | None | Specifies an array of paths of markdown files or folders | +| Markdown | None | Specifies a string that contains markdown formatted text | + +#### Merge-MarkdownHelp + +| ParamName | DefaultValue | Description | +| ----------------------- | ---------------- | ------------------------------------------------------------------------------------- | +| Encoding | UTF8 without BOM | Specifies the character encoding for your external help file. Specify a System.Text.E | +| ExplicitApplicableIfAll | False | Always write out full list of applicable tags. By default cmdlets and parameters that | +| Force | False | Indicates that this cmdlet overwrites an existing file that has the same name | +| MergeMarker | '!!! ' | String to be used as a merge text indicator. Applicable tag list would be included | +| OutputPath | None | Specifies the path of the folder where this cmdlet creates the combined markdown help | +| Path | None | Specifies an array of paths of markdown files or folders. This cmdlet creates | + +#### New-ExternalHelp + +| ParamName | DefaultValue | Description | +| ------------- | ---------------- | ----------------------------------------------------------------------------------------------- | +| OutputPath | None | Specifies the path of a folder where this cmdlet saves your external help file. The folder name | +| Encoding | UTF8 without BOM | Specifies the character encoding for your external help file. Specify a System.Text.Encoding | +| Force | False | Indicates that this cmdlet overwrites an existing file that has the same name | +| Path | None | Specifies an array of paths of markdown files or folders. This cmdlet creates external help | +| ApplicableTag | None | Specify array of tags to use as a filter. If cmdlet has `applicable` in the yaml metadata | +| MaxAboutWidth | 80 | Specifies the maximimum line length when generating "about" help text files. | +| ErrorLogFile | None | The path where this cmdlet will save formatted results log file | +| ShowProgress | False | Display progress bars under parsing existing markdown files | + +#### New-ExternalHelpCab + +| ParamName | DefaultValue | Description | +| -------------------- | ------------ | ------------------------------------------------------------------------------------------- | +| CabFilesFolder | None | Specifies the folder that contains the help content that this cmdlet packages into a .cab | +| LandingPagePath | None | Specifies the full path of the Module Markdown file that contains all the metadata required | +| OutputFolder | None | Specifies the location of the .cab file and helpinfo.xml file that this cmdlet creates | +| IncrementHelpVersion | False | Automatically increment the help version in the module markdown file | + +#### New-MarkdownAboutHelp + +| ParamName | DefaultValue | Description | +| ------------ | ------------ | ------------------------------------------ | +| AboutName | None | The name of the about topic | +| OutputFolder | None | The directory to create the about topic in | + +#### New-MarkdownHelp + +| ParamName | DefaultValue | Description | +| ---------------------- | ---------------- | --------------------------------------------------------------------------------------- | +| Command | None | Specifies the name of a command in your current session. This can be any command | +| Encoding | UTF8 without BOM | Specifies the character encoding for your markdown help files | +| Force | False | Indicates that this cmdlet overwrites existing files that have the same names | +| FwLink | None | Specifies the forward link for the module page. This value is required for .cab | +| HelpVersion | None | Specifies the version of your help. This value is required for .cab file creation | +| Locale | None | Specifies the locale of your help. This value is required for .cab file creation | +| MamlFile | None | Specifies an array of paths path of MAML .xml help files | +| Metadata | None | Specifies metadata that this cmdlet includes in the help markdown files as a hash table | +| Module | None | Specifies an array of names of modules for which this cmdlet creates help in markdown | +| ModuleGuid | None | Specifies the GUID of the module of your help. This value is required for .cab file | +| ModuleName | None | Specifies the name of the module of your help. This value is required for .cab file | +| NoMetadata | False | Indicates that this cmdlet does not write any metadata in the generated markdown | +| OnlineVersionUrl | None | Specifies the URL where the updatable help function downloads updated help | +| OutputFolder | None | Specifies the path of the folder where this cmdlet creates the markdown help files | +| WithModulePage | False | Indicates that this cmdlet creates a module page in the output folder | +| ConvertNotesToList | False | Indicates that this cmldet formats multiple paragraph items in the NOTES section | +| ConvertDoubleDashLists | False | Indicates that this cmldet converts double-hyphen list bullets into single-hyphen | +| AlphabeticParamsOrder | False | Order parameters alphabetically by name in PARAMETERS section. There are 5 exceptions | +| UseFullTypeName | False | Indicates that the target document will use a full type name instead of a short name | +| Session | None | Provides support for remote commands. Pass the session that you used to create | +| ModulePagePath | None | When WithModule parameter is used by default it puts .md file in same location as all | +| ExcludeDontShow | False | Exclude the parameters marked with `DontShow` in the parameter attribute from the help | + +#### New-YamlHelp + +| ParamName | DefaultValue | Description | +| ------------ | ------------ | --------------------------------------------------------------------------------------------------- | +| Encoding | None | Specifies the character encoding for your external help file. Specify a System.Text.Encoding object | +| Force | False | Indicates that this cmdlet overwrites an existing file that has the same name | +| Path | None | Specifies an array of paths of markdown files or folders | +| OutputFolder | None | Specifies the folder to create the YAML files | + +#### Update-MarkdownHelp + +| ParamName | DefaultValue | Description | +| --------------------- | ---------------- | ------------------------------------------------------------------------------------ | +| Encoding | UTF8 without BOM | Specifies the character encoding for your markdown help files | +| LogAppend | False | Indicates that this cmdlet appends information to the log instead overwriting it | +| LogPath | None | Specifies a file path for log information. The cmdlet writes the VERBOSE stream | +| Path | None | Specifies an array of paths of markdown files and folders to update | +| AlphabeticParamsOrder | False | Order parameters alphabetically by name in PARAMETERS section | +| UseFullTypeName | False | Indicates that the target document will use a full type name instead of a short name | +| Session | None | Provides support for remote commands. Pass the session that you used to create | +| UpdateInputOutput | False | Refreshes the Input and Output section to reflect the current state of the cmdlet | +| Force | False | Remove help files that no longer exists within sessions | +| ExcludeDontShow | False | Exclude the parameters marked with `DontShow` in the parameter attribute | + +#### Update-MarkdownHelpModule + +| ParamName | DefaultValue | Description | +| --------------------- | ---------------- | -------------------------------------------------------------------------------------- | +| Encoding | UTF8 without BOM | Specifies the character encoding for your markdown help files | +| LogAppend | False | Indicates that this cmdlet appends information to the log instead overwriting | +| LogPath | None | Specifies a file path for log information. The cmdlet writes the VERBOSE stream | +| Path | None | Specifies an array of paths of markdown folders to update. The folder must contain | +| RefreshModulePage | False | Update module page when updating the help module | +| AlphabeticParamsOrder | False | Order parameters alphabetically by name in PARAMETERS section | +| Session | None | Provides support for remote commands. Pass the session that you used to create | +| UseFullTypeName | False | Indicates that the target document will use a full type name instead of a short name | +| UpdateInputOutput | False | Refreshes the Input and Output sections to reflect the current state of the cmdlet | +| ModulePagePath | None | When -RefreshModulePage is used by default it puts .md file in same location | +| Force | False | Remove help files that no longer exists within sessions | +| ExcludeDontShow | False | Exclude the parameters marked with `DontShow` in the parameter attribute from the help | + +## Cmdlet Feature requests + +1. I was wondering if we should default to zips instead, one package for both platforms. Cabs as + legacy for < 5.1 content. We can fix PS 7.2 to look for zip first and fallback to cab. Add as + question in spec — This should be a switch - cab, zip or both. + +1. Need to know about Merge-MarkdownHelp which uses `applicable:` yaml syntax for version. + `applicable:` should be mentioned in the schema. — this creates tags…for linux/windows + parameters. Exchange uses the `applicable:` feature heavily. Need to maintain support for them. + +1. Need way to increment the help version number of the CAB files + + - Could be automatic in every build? + - Could be scheduled? + - Could be a workflow step (scripted) done by the author + - Need to figure out limits of version number fields + - Need rules for when to increment major, minor, subminor, etc. (Semvar?) + +### List of things that break with PS5.1 or Exchange + +TODO diff --git a/docs/Microsoft.PowerShell.PlatyPS/specs/platyps_2.0_update.md b/docs/Microsoft.PowerShell.PlatyPS/specs/platyps_2.0_update.md new file mode 100644 index 00000000..98ff28d3 --- /dev/null +++ b/docs/Microsoft.PowerShell.PlatyPS/specs/platyps_2.0_update.md @@ -0,0 +1,289 @@ +--- +title: PlatyPS 2.0 specification +ms.date: 03/09/2023 +--- + +# PlatyPS 2.0 Update + +PlatyPS provides module owners with the ability to write PowerShell External Help in MarkDown. +PlatyPS generates downloadable and updatable help. + +## For this update + +PlatyPS expects Markdown to be authored in a particular way. We have defined a schema to determine +how parameters are described, where scripts examples are shown, and so on. The schema closely +resembles the existing output format of the `Get-Help` cmdlet in PowerShell. One of the primary +goals of this update is to improve the schema. The goal of 2.0.0 release is to maintain +compatibility while fixing the longstanding issues. + +This update includes the following goals: + +Priorities + +- Fix schema so that it contains all the Help Data we need while maintaining as much + compatibility as possible with PS 5.1 and Exchange +- Switch markdown engine to markdig +- Fix OPS rendering problems (requires specific changes in PlatyPS and OPS) + +After the initial release, we should look at new features and consider whether we fork the tool to a +new no-legacy feature set or try to maintain compatibility going forward (ala PowerShellGet 3.0). + +## Motivation + +PowerShell external help files have been authored by hand or using complex tool chains and rendered +as MAML XML for use as console help. MAML is cumbersome to edit by hand, and common tools and +editors don't support it for complex scenarios like they do with Markdown. PlatyPS is provided as a +solution for allow documenting PowerShell help in any editor or tool that supports Markdown. + +An additional challenge PlatyPS tackles, is to handle PowerShell documentation for complex scenarios +(e.g. very large, closed source, and/or C#/binary modules) where it may be desirable to have +documentation abstracted away from the codebase. PlatyPS does not need source access to generate +documentation. + +Markdown is designed to be human-readable, without rendering. This makes writing and editing easy +and efficient. Many editors support it (Visual Studio Code, Sublime Text, etc), and many tools and +collaboration platforms (GitHub, Visual Studio Online) render the Markdown nicely. + +## Release plan + +- Proposed Preview + - TODO + +## Goals/Non-Goals + + Goals: + +- Update the Help file schema +- Update the About_ schema +- Update the cmdlet parameters to remove/add improvements +- TODO + +Non-goals: + +- TODO + +## Specification + +The proposal is to update the functionality and schema of PlayPS to improve the module owners +experience building and updating Help. + +### Schema for cmdlet reference + +The following sections outline schema changes for the Help file. + +| Heading | Level | Required? | Count | Description | +| ------------------ | ----- | --------- | ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Title | H1 | Y | 1 | - No changes | +| Synopsis | H2 | Y | 1 | - No changes | +| Aliases | H2 | Y | 1 | - New header to support documentation for cmdlet aliases | +| Syntax | H2 | Y | 1 | - No changes | +| Parameter Set Name | H3 | Y | 1-N | - Parameter Sets - should be sorted starting with Default, then by Alpha
- Parameters (in syntax block) - Should be sorted Positional, Required, then by Alpha | +| Description | H2 | Y | 1 | - Allow any content type
- No Headers H2, H3, H4 | +| Examples | H2 | Y | 1 | - No changes | +| Example | H3 | Y | 1-N | - Should require one code block at minimum per example
- Should not be restricted on elements or size | +| Parameters | H2 | Y | 1 | - Parameters Should be sorted Alpha. Currently PlatyPS has a switch to force Alpha versus enumerated. The default is off, please change to On. | +| Parameter | H3 | Y | 1-N | - Yaml block should include:
- Parameter Set Name
- AcceptedValues - Should display enumerated values of parameter (like ValidateSet)
- ConfirmImpact - Impact severity should be reflected and displayed to inform defaults for -Confirm | +| Common Parameters | H3 | Y | 1 | - Change the fwlink to remove local and version | +| Inputs | H2 | Y | 1 | - Add cross reference link to the API reference for the input/output object type
- [xref link docs][06] | +| Input type | H3 | N | 0-N | | +| Outputs | H2 | Y | 1 | - Add cross reference link to the API reference for the input/output object type
- [xref link docs][06] | +| Output type | H3 | N | 0-N | | +| Notes | H2 | N | 1 | Mandatory for schema but not rendered by OPS if empty | +| Related links | H3 | Y | 1 | - Link list should use bullets
- PlatyPS needs to support bullets
- Should support Text (prose), not just links | + +#### Updated YAML structure for parameters + +The following example shows the markdown for the Yaml metadata of a parameter. The Yaml block +contains new metadata items. + +~~~markdown +```yaml +Type: System.Management.Automation.ScopedItemOptions +Parameter Sets: (All) +Aliases: +Required: False +Position: Named +Default value: None +Accept pipeline input: ByValue (False), ByName (False) +Accept wildcard characters: False +Dynamic: True +Providers: Alias, Function +Values from remaining args: False +Do not show: False +Is credential: False +Is obsolete: False +Release status: Feature Preview +``` +~~~ + +Notes + +- Values for most items should be obtained by reflection. +- Provider information will have to be tested individually based on the currently loaded providers. +- The `Default value` should be obtained by reflection, if possible. + - The default value for **SwitchParameter** types should be `False`. +- If possible, the `Parameter sets` and `Providers` values should be simplified to show `(All)` when + the value is the same for all parameter sets or providers. + +New metadata + +- `Dynamic` + - Type: boolean + - Obtained by reflection of parameter attributes + - Required +- `Providers` + - Type: string containing one or more provider names (comma-separated) + - Optional - expected when `Dynamic` is true +- `Values from remaining args` + - Type: boolean + - Obtained by reflection of parameter attributes + - Required +- `Do not show` + - Type: boolean + - Obtained by reflection of parameter attributes + - Required +- `Is credential` + - Type: boolean + - Obtained by reflection of parameter attributes + - Required +- `Is obsolete` + - Type: boolean + - Obtained by reflection of parameter attributes + - Required +- `Release status` + - Type: string representation of one enum value from: + - 'Preview' - typically not used for parameters + - 'Feature Preview' - typically not used for parameters + - 'Experimental' - used for parameters that are enabled by a PowerShell experimental feature + - 'Deprecated' - used for cmdlet that will be unsupported after a certain date are removed in a + future release + - Null value - indicates the parameter is GA (currently supported) + - Optional - the value can be null or the key-value pair omitted + +The OPS build pipeline should validate that the values match the type. `Release status` should only +be rendered on the page if the key has a value (not null). + +### Schema updates for cmdlet frontmatter + +#### Cmdlet alias metadata + +Have a way to document aliases for the cmdlet. Today we only document aliases for parameters. This +is difficult to discover, so don't need `*-MarkdownHelp` cmdlets to create it but the schema needs +to support it. The author can add the information to the YAML frontmatter. For example: + +```yaml +aliases: [dir, gci, ls] +``` + +Add new H2 for documenting aliases. + +```markdown +## ALIASES + +PowerShell includes the following aliases for `Get-ChildItem`: + +- All platforms: `dir`, `gci` +- Windows: `ls` +``` + +See [alias-prototype][02] for a more complete example. + +> [!NOTE] +> The `aliases` metadata is optional. The information will be added by the documentation author. The +> ALIASES H2 section is optional and will be added by the documentation author as necessary. The +> reference pipeline shouldn't try to validate this content or metadata values. The reference +> pipeline should add all aliases to the `displayname` property of the Yaml TOC entry for the +> cmdlet. For more information about the `displayname` property, see the [TOC docs][07]. + +See [Issue #585][04]. + +#### Cmdlet platform availability + +The purpose of this is to represent the availability of the cmdlet for a platform (win/mac/linux). +Could be one or more. PlatyPS could default to Windows when creating the markdown. The value should +be edited by the author to ensure accuracy. + +```yaml +- platforms: [win, macOS, linux] +``` + +- `platforms` + - Type: string array containing one or more platform names (win, macOS, linux) + - Required + +The reference build pipeline should enforce the requirement but doesn't need to use the values + +#### Cmdlet release status metadata + +The purpose of this metadata is to represent the release status of the cmdlet. The value isn't +required if the cmdlet is GA. This metadata will be added by the author as necessary. + +PlatyPS should create the metadata as placeholders in the frontmatter. The author should delete the +keys or update the values as appropriate. + +```yaml +release: + status : Preview, Feature Preview, Experimental, Deprecated + message : Text of a banner message. +``` + +- `release` + - Type: string representation of one enum value from: + - 'Preview', 'Feature Preview', 'Experimental', 'Deprecated' + - Optional +- `status` + - Type: string representation of one enum value from: + - 'Preview' - used for cmdlets from preview modules where the version is 0.x.y with no + Prerelease label + - 'Feature Preview' - used for cmdlets from feature preview modules where the version is 1.x.y + or higher and has a Prerelease label + - 'Experimental' - used for cmdlets that are enabled by a PowerShell experimental feature + - 'Deprecated' - used for cmdlet that will be unsupported after a certain date are removed in a + future release + - Required +- `message` + - Type: string - text of an alert message to be displayed in the documentation + - The message should be a single sentence or short paragraph. Include end of support dates if + applicable. + - Required + +The reference build pipeline should do the following: + +- Use the `status` to select the badge displayed for the status. +- Use the `message` to render an alert box on the page containing the message +- Validate that the values match the types. + +Matt Trilby-Bassett has some [Figma designs][08] showing the badge and alert box. + +### Schema for Module file frontmatter + +The `Module.md` file is the landing page for a module and is used during conversion to MAML. The +frontmatter for this file will also include the `release` metadata for non-GA modules. + +See the [release status metadata][01] described above. + +The reference build pipeline will use: + +- the `status` to select the badge displayed for the status. +- the `message` to render an alert box on the page containing the message + +### PlatyPS formatting changes + +- General + - Would like PlatyPS to add a line break after each Markdown block + - Example - Headers, Code blocks, Lists + - Bug: `Get-Help`: Requires that the first line of text be immediately following Synopsis header + +## Issues for this milestone + +[2.0-consider][03] + + +[01]: #cmdlet-release-status-metadata +[02]: alias-prototype.md +[03]: https://github.com/PowerShell/platyPS/issues?q=is%3Aopen+is%3Aissue+milestone%3A2.0-consider +[04]: https://github.com/PowerShell/platyPS/issues/585 +[05]: https://github.com/PowerShell/PowerShell/issues/9208 +[06]: https://review.docs.microsoft.com/en-us/help/contribute/links-how-to?branch=master#xref-cross-reference-links +[07]: https://review.learn.microsoft.com/en-us/help/platform/navigation-toc-overview?branch=main#yaml-toc-format +[08]: https://www.figma.com/file/EP3wMMct92SqHwvWcorb9O/%5BDiscovery%5D-Reference-Development-Status-Information?node-id=897%3A3314&t=zy1ygL7Gh5ChSyh1-0 diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 00000000..b73d8d9c --- /dev/null +++ b/docs/README.md @@ -0,0 +1,35 @@ +# PlatyPS design documentation + +This repository contains the source code for the legacy version of PlatyPS and the new version. + +## Branches + +- `main`: Contains the source code for the new version of PlatyPS named + **Microsoft.PowerShell.PlatyPS**. This is the current supported version of PlatyPS. You can find + this version listed as [Microsoft.PowerShell.PlatyPS][04] in the PowerShell Gallery. +- `v1`: Contains the source code for the legacy version of PlatyPS named **platyPS**. This version + is no longer actively maintained, but it is available for reference and legacy support. The latest + version of this code is 0.14.2. You can find this version listed as [platyPS][05] in the the + PowerShell Gallery. + +## Folder structure + +This folder contains design documentation for the PlatyPS project. This documentation is targeted at +developers and contributors to the project. + +- [Microsoft.PowerShell.PlatyPS][01]: Contains the design documents for the current version of + PlatyPS. +- [platyPS][03]: Contains the design documents for the legacy version of the module. + +## Contributing + +We no longer accept issues for or contributions to the legacy version of PlatyPS. For more +information about contributing to the new version of PlatyPS, please see the +[contributing guide][02]. + + +[01]: ./Microsoft.PowerShell.PlatyPS +[02]: ./Microsoft.PowerShell.PlatyPS/CONTRIBUTING.md +[03]: ./platyPS +[04]: https://www.powershellgallery.com/packages/Microsoft.PowerShell.PlatyPS +[05]: https://www.powershellgallery.com/packages/platyPS/0.14.2 diff --git a/docs/platyPS/CONTRIBUTING.md b/docs/platyPS/CONTRIBUTING.md new file mode 100644 index 00000000..c0a901cd --- /dev/null +++ b/docs/platyPS/CONTRIBUTING.md @@ -0,0 +1,138 @@ +# Contributing to platyPS + +## Get the code + +``` +git clone https://github.com/PowerShell/platyPS +``` + +## Understand code layout + +There are two parts: + +- `Markdown.MAML.dll`, a .NET library written in C#. It does the heavy lifting, like parsing + Markdown, transforming it into XML, and so on. You can open `.\Markdown.MAML.sln` in Visual Studio + on any platform. +- A PowerShell module in `.\src\platyPS`. This module provides the user CLI. + +## Build + +To build the whole project, use the `build.ps1` helper script. It depends on the [dotnet cli][01] +build tool. + +On Windows you would also need to [install full dotnet framework][02] if it's not installed already. + +```powershell +.\build.ps1 +``` + +As part of the build, platyPS generates help for itself. The output of the build is placed in +`out\Microsoft.PowerShell.PlatyPS`. + +`build.ps1` also imports the module from `out\platyPS` and generates help itself. + +> [!NOTE] +> If you changed C# code, `build.ps1` will try to overwrite a DLL in use. You will then need to +> re-open your PowerShell session. If you know a better workflow, please suggest it in the Issues. + +## Tests + +Each part of the project has a test set: + +- The C# part has xUnit tests. You can run them from Visual Studio or from command line with + `dotnet test ./test/Markdown.MAML.Test`. +- The PowerShell part has [Pester][03] tests. You can run them with `Invoke-Pester`. + +> [!NOTE] +> Pester tests always force-import the module from the output location of `.\build.ps1`. + +## Schema + +If you have ideas or concerns about the Markdown schema, feel free to open a GitHub Issue to discuss +it. + +## Repo structure + +- **src\platyPS** - sources to create the final PowerShell module. +- **src\Markdown.MAML, Markdown.MAML.sln** - source code for C# Markdown to MAML converter. +- **[platyPS.schema.md][04]** - description of Markdown that platyPS expects. + +## Data transformations + +Data transformations are the core of platyPS. A user has content in some form and she wants to +transform it into another form. E.g. transform existing module help (in MAML) to Markdown and use it +in the future to generate the external help (MAML) and static HTML for online references. + +platyPS provides APIs in the form of cmdlets for end-user scenarios. These scenarios are assembled +from simple transformations. This chart describes these simple transformations: + +``` + +----------+ + | | + | HTML | + | | + +------^---+ + | + +------+------------+ +-----------------+ + | | | Markdown Model | + | Markdown file +-----------> | + | | +-+---------------+ + | | | + +---------------^---+ | + | | + | | + | | + +--+-----------------v--+ + | MAML Model | + | (= Generic Help model)| + | | + +--+-------------------^+ + | | + | | + | | ++----------------v-----+ ++--------------------------+ +| MAML XML file | | Help Object in PowerShell | +| (External help file) +------------> (+ Get-Command object) | ++----------------------+ +---------------------------+ +``` + +### Example `New-MarkdownHelp` + +A user creates a platyPS Markdown for the first time with `New-MarkdownHelp`: + +```powershell +New-MarkdownHelp -Command New-MyCommandHelp +``` + +Under the hood, the following tranformations happen: + +``` +[MAML XML file] --> [Help Object + Get-Command object] --> [MAML Model] --> [Markdown file] +``` + +# Making a new release + +1. Make sure that `CHANGELOG.md` is up-to-date, move section from `UNRELEASED` to new section + ``. +1. Make sure platyPS help itself (content in .\docs folder) is up to date. + `Update-MarkdownHelp -Path .\docs` should result in no changes. +1. Do not change the version in platyps.psd1. Git tag will update this version for release. +1. From master, tag the release. +1. Push tag to GitHub. +1. Find the corresponding build on AppVeyor. +1. Download ZIP archive with the module from Appveyor's Artifacts tab. +1. Unblock the ZIP archive (`Unblock-File foo.zip`), and copy the ZIP's contents to + `$env:PSMODULEPATH` so it's available to `Publish-Module`. +1. Publish the module to the Gallery: + `Publish-Module -RequiredVersion -Verbose -NuGetApiKey $apiKey`. +1. Check that https://www.powershellgallery.com/packages/platyPS/ updated. +1. Publish a new github release from https://github.com/PowerShell/platyPS/releases to move "Latest + release" label to the new tag. + +Congratulations! You just made a release. + + +[01]: https://docs.microsoft.com/en-us/dotnet/core/tools/ +[02]: https://docs.microsoft.com/en-us/dotnet/framework/install/guide-for-developers +[03]: https://github.com/pester/Pester +[04]: platyPS.schema.md diff --git a/v1/platyPS.schema.md b/docs/platyPS/platyPS.schema.md similarity index 100% rename from v1/platyPS.schema.md rename to docs/platyPS/platyPS.schema.md diff --git a/presentation/css/impress-demo.css b/docs/platyPS/presentation/css/impress-demo.css similarity index 100% rename from presentation/css/impress-demo.css rename to docs/platyPS/presentation/css/impress-demo.css diff --git a/presentation/images/FFFUUU.png b/docs/platyPS/presentation/images/FFFUUU.png similarity index 100% rename from presentation/images/FFFUUU.png rename to docs/platyPS/presentation/images/FFFUUU.png diff --git a/presentation/images/azure-maml.png b/docs/platyPS/presentation/images/azure-maml.png similarity index 100% rename from presentation/images/azure-maml.png rename to docs/platyPS/presentation/images/azure-maml.png diff --git a/presentation/images/get-help.png b/docs/platyPS/presentation/images/get-help.png similarity index 100% rename from presentation/images/get-help.png rename to docs/platyPS/presentation/images/get-help.png diff --git a/presentation/images/markdown-github.png b/docs/platyPS/presentation/images/markdown-github.png similarity index 100% rename from presentation/images/markdown-github.png rename to docs/platyPS/presentation/images/markdown-github.png diff --git a/presentation/images/markdown.png b/docs/platyPS/presentation/images/markdown.png similarity index 100% rename from presentation/images/markdown.png rename to docs/platyPS/presentation/images/markdown.png diff --git a/presentation/images/pscmdlethelpeditor.png b/docs/platyPS/presentation/images/pscmdlethelpeditor.png similarity index 100% rename from presentation/images/pscmdlethelpeditor.png rename to docs/platyPS/presentation/images/pscmdlethelpeditor.png diff --git a/presentation/images/psreadline-maml.png b/docs/platyPS/presentation/images/psreadline-maml.png similarity index 100% rename from presentation/images/psreadline-maml.png rename to docs/platyPS/presentation/images/psreadline-maml.png diff --git a/presentation/index.html b/docs/platyPS/presentation/index.html similarity index 100% rename from presentation/index.html rename to docs/platyPS/presentation/index.html diff --git a/presentation/js/impress.js b/docs/platyPS/presentation/js/impress.js similarity index 100% rename from presentation/js/impress.js rename to docs/platyPS/presentation/js/impress.js diff --git a/v1/.travis.yml b/v1/.travis.yml deleted file mode 100644 index c260d807..00000000 --- a/v1/.travis.yml +++ /dev/null @@ -1,24 +0,0 @@ -# that gives us dotnet cli installed on the box -language: csharp - -dist: trusty -sudo: required - -mono: none -dotnet: 2.0.0 - -# instruction from https://github.com/PowerShell/PowerShell/blob/master/docs/installation/linux.md#ubuntu-1404 - -install: - - curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add - - - curl https://packages.microsoft.com/config/ubuntu/14.04/prod.list | sudo tee /etc/apt/sources.list.d/microsoft.list - - sudo apt-get update - - sudo apt-get install -y powershell=6.0.2-1.ubuntu.14.04 - -script: - - pwsh ./build.ps1 - - dotnet test ./test/Markdown.MAML.Test - - sudo pwsh -C 'Install-Module Pester -Force' - # updated help is needed for tests, run as a Job to avoid Write-Progress output - - sudo pwsh -C '(update-help &) | Wait-Job' - - pwsh -C 'Invoke-Pester -EnableExit' diff --git a/v1/Markdown.MAML.sln b/v1/Markdown.MAML.sln deleted file mode 100644 index 51ea0f47..00000000 --- a/v1/Markdown.MAML.sln +++ /dev/null @@ -1,36 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0.31101.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{13CF312C-8A3D-4AFC-87F2-B84E00E8BC72}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{41E87F18-4D5D-46B6-9DF8-28FB90760F0B}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Markdown.MAML", "src\Markdown.MAML\Markdown.MAML.csproj", "{9AFC25E8-6BAF-4B6B-B33F-CC2E0496E9C0}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Markdown.MAML.Test", "test\Markdown.MAML.Test\Markdown.MAML.Test.csproj", "{317CCB63-9AFA-4647-8838-DD8E20C8716F}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {9AFC25E8-6BAF-4B6B-B33F-CC2E0496E9C0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9AFC25E8-6BAF-4B6B-B33F-CC2E0496E9C0}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9AFC25E8-6BAF-4B6B-B33F-CC2E0496E9C0}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9AFC25E8-6BAF-4B6B-B33F-CC2E0496E9C0}.Release|Any CPU.Build.0 = Release|Any CPU - {317CCB63-9AFA-4647-8838-DD8E20C8716F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {317CCB63-9AFA-4647-8838-DD8E20C8716F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {317CCB63-9AFA-4647-8838-DD8E20C8716F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {317CCB63-9AFA-4647-8838-DD8E20C8716F}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {9AFC25E8-6BAF-4B6B-B33F-CC2E0496E9C0} = {13CF312C-8A3D-4AFC-87F2-B84E00E8BC72} - {317CCB63-9AFA-4647-8838-DD8E20C8716F} = {41E87F18-4D5D-46B6-9DF8-28FB90760F0B} - EndGlobalSection -EndGlobal diff --git a/v1/appveyor.yml b/v1/appveyor.yml deleted file mode 100644 index 3f444e08..00000000 --- a/v1/appveyor.yml +++ /dev/null @@ -1,63 +0,0 @@ -version: 0.11.0.{build} - -install: - - ps: | - Write-Host "PowerShell Version:" $PSVersionTable.PSVersion.tostring() - Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force - Install-Module -Name Pester -RequiredVersion 4.10.1 -Force - -init: - - git config --global core.autocrlf true - -build_script: - - ps: | - $ErrorActionPreference = 'Stop' - Update-Help Microsoft.PowerShell.Core, Microsoft.PowerShell.Management, Microsoft.PowerShell.Utility -Force # we need up-to-date help content for tests - .\build.ps1 -Configuration Release - -test_script: - - dotnet test .\test\Markdown.MAML.Test - -after_test: - - ps: | - # We run Pester tests in after_test step - # we don't want to use test_script - # appveyor doesn't run after_test, if tests failed. - # - # Pester tests produce artifacts in .\out directory - $pesterTestResultsFile = ".\TestsResults.xml" - $res = Invoke-Pester -OutputFormat NUnitXml -OutputFile $pesterTestResultsFile -PassThru - (New-Object 'System.Net.WebClient').UploadFile("https://ci.appveyor.com/api/testresults/nunit/$($env:APPVEYOR_JOB_ID)", (Resolve-Path $pesterTestResultsFile)) - # Trying to fail the build, if there are problems - $errorString = '' - # All tests should pass - if ($res.FailedCount -gt 0) { - $errorString += "$($res.FailedCount) tests failed.`n" - } - # Documentation itself should be up-to-date - Update-MarkdownHelp -Path ./docs - $diff = git diff - if ($diff) { - $errorString += "Help is not up-to-date, run Update-MarkdownHelp: $diff`n" - } - if ($errorString) { - throw $errorString - } - -on_finish: - - ps: | - $ErrorActionPreference = 'Stop' - try { - $stagingDirectory = (Resolve-Path ..).Path - $zipFile = Join-Path $stagingDirectory "platyPS-$($env:APPVEYOR_BUILD_VERSION).zip" - Add-Type -assemblyname System.IO.Compression.FileSystem - 7z a -tzip $zipFile "$pwd\out\platyPS" - @( - # You can add other artifacts here - (ls $zipFile), - (ls .\out -File) - # flattering - ) | % {$_} | ? {$_} |% { Push-AppveyorArtifact $_.FullName } - } catch { - Write-Host -Foreground Red $_ - } diff --git a/v1/build.ps1 b/v1/build.ps1 deleted file mode 100644 index e9de3bca..00000000 --- a/v1/build.ps1 +++ /dev/null @@ -1,86 +0,0 @@ -<# -.SYNOPSIS - Builds the MarkDown/MAML DLL and assembles the final package in out\platyPS. -#> -[CmdletBinding()] -param( - [ValidateSet('Debug', 'Release')] - $Configuration = "Debug", - [switch]$SkipDocs, - [string]$DotnetCli -) - -function Find-DotnetCli() -{ - [string] $DotnetCli = '' - $dotnetCmd = Get-Command dotnet - return $dotnetCmd.Path -} - - -if (-not $DotnetCli) { - $DotnetCli = Find-DotnetCli -} - -if (-not $DotnetCli) { - throw "dotnet cli is not found in PATH, install it from https://docs.microsoft.com/en-us/dotnet/core/tools" -} else { - Write-Host "Using dotnet from $DotnetCli" -} - -if (Get-Variable -Name IsCoreClr -ValueOnly -ErrorAction SilentlyContinue) { - $framework = 'netstandard1.6' -} else { - $framework = 'net451' -} - -& $DotnetCli publish ./src/Markdown.MAML -f $framework --output=$pwd/publish /p:Configuration=$Configuration - -$assemblyPaths = ( - (Resolve-Path "publish/Markdown.MAML.dll").Path, - (Resolve-Path "publish/YamlDotNet.dll").Path -) - -# copy artifacts -New-Item -Type Directory out -ErrorAction SilentlyContinue > $null -Copy-Item -Rec -Force src\platyPS out -foreach($assemblyPath in $assemblyPaths) -{ - $assemblyFileName = [System.IO.Path]::GetFileName($assemblyPath) - $outputPath = "out\platyPS\$assemblyFileName" - if ((-not (Test-Path $outputPath)) -or - (Test-Path $outputPath -OlderThan (Get-ChildItem $assemblyPath).LastWriteTime)) - { - Copy-Item $assemblyPath out\platyPS - } else { - Write-Host -Foreground Yellow "Skip $assemblyFileName copying" - } -} - -# copy schema file and docs -Copy-Item .\platyPS.schema.md out\platyPS -New-Item -Type Directory out\platyPS\docs -ErrorAction SilentlyContinue > $null -Copy-Item .\docs\* out\platyPS\docs\ - -# copy template files -New-Item -Type Directory out\platyPS\templates -ErrorAction SilentlyContinue > $null -Copy-Item .\templates\* out\platyPS\templates\ - -# put the right module version -if ($env:APPVEYOR_REPO_TAG_NAME) -{ - $manifest = cat -raw out\platyPS\platyPS.psd1 - $manifest = $manifest -replace "ModuleVersion = '0.0.1'", "ModuleVersion = '$($env:APPVEYOR_REPO_TAG_NAME)'" - Set-Content -Value $manifest -Path out\platyPS\platyPS.psd1 -Encoding Ascii -} - -# dogfooding: generate help for the module -Remove-Module platyPS -ErrorAction SilentlyContinue -Import-Module $pwd\out\platyPS - -if (-not $SkipDocs) { - New-ExternalHelp docs -OutputPath out\platyPS\en-US -Force - # reload module, to apply generated help - Import-Module $pwd\out\platyPS -Force -} - diff --git a/v1/docs/Get-HelpPreview.md b/v1/docs/Get-HelpPreview.md deleted file mode 100644 index 651db8f1..00000000 --- a/v1/docs/Get-HelpPreview.md +++ /dev/null @@ -1,111 +0,0 @@ ---- -external help file: platyPS-help.xml -Module Name: platyPS -online version: https://github.com/PowerShell/platyPS/blob/master/docs/Get-HelpPreview.md -schema: 2.0.0 ---- - -# Get-HelpPreview - -## SYNOPSIS -Displays your generated external help as **Get-Help** output. - -## SYNTAX - -``` -Get-HelpPreview -Path [-ConvertNotesToList] [-ConvertDoubleDashLists] [] -``` - -## DESCRIPTION -The **Get-HelpPreview** cmdlet displays your generated external help as **Get-Help** output. -Specify one or more files in Microsoft Assistance Markup Language (MAML) format. - -## EXAMPLES - -### Example 1: Preview the PlatyPS help -``` -PS C:\> $Help = Get-HelpPreview -Path ".\out\platyPS\en-US\PlatyPS-help.xml" - -PS C:\> $Help.Name - -Get-HelpPreview -Get-MarkdownMetadata -New-ExternalHelp -New-ExternalHelpCab -New-MarkdownHelp -Update-MarkdownHelp -Update-MarkdownHelpModule -Update-MarkdownHelpSchema -``` - -The first command creates a **Help** object for the the specified MAML file. -The command stores it in the $Help variable. - -The second command displays the **Name** property for each of the objects in $Help. - -## PARAMETERS - -### -Path -Specifies an array of paths of MAML external help files. - -```yaml -Type: String[] -Parameter Sets: (All) -Aliases: - -Required: True -Position: Named -Default value: None -Accept pipeline input: True (ByValue) -Accept wildcard characters: True -``` - -### -ConvertNotesToList -Indicates that this cmldet formats multiple paragraph items in the **NOTES** section as single list items. -This output follows TechNet formatting. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -ConvertDoubleDashLists -Indicates that this cmldet converts double-hyphen list bullets into single-hyphen bullets. -Double-hyphen lists are common in Windows PowerShell documentation. -Markdown accepts single-hyphens for lists. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### String[] -You can pipe an array of paths to this cmdlet. - -## OUTPUTS - -### Help Object -This cmdlet returns a **Help** object, which is the same output as **Get-Help**. - -## NOTES - -## RELATED LINKS diff --git a/v1/docs/Get-MarkdownMetadata.md b/v1/docs/Get-MarkdownMetadata.md deleted file mode 100644 index dad4e873..00000000 --- a/v1/docs/Get-MarkdownMetadata.md +++ /dev/null @@ -1,138 +0,0 @@ ---- -external help file: platyPS-help.xml -Module Name: platyPS -online version: https://github.com/PowerShell/platyPS/blob/master/docs/Get-MarkdownMetadata.md -schema: 2.0.0 ---- - -# Get-MarkdownMetadata - -## SYNOPSIS -Gets metadata from the header of a markdown file. - -## SYNTAX - -### FromPath (Default) -``` -Get-MarkdownMetadata -Path [] -``` - -### FromMarkdownString -``` -Get-MarkdownMetadata -Markdown [] -``` - -## DESCRIPTION -The **Get-MarkdownMetadata** cmdlet gets the metadata from the header of a markdown file that is supported by PlatyPS. -The command returns the metadata as a hash table. - -PlatyPS stores metadata in the header block of a markdown file as key-value pairs of strings. -By default, PlatyPS stores help file name and markdown schema version. - -Metadata section can contain user-provided values for use with external tools. -The [New-ExternalHelp](New-ExternalHelp.md) cmdlet ignores this metadata. - -## EXAMPLES - -### Example 1: Get metadata from a file -``` -PS C:\> Get-MarkdownMetadata -Path ".\docs\Get-MarkdownMetadata.md" - -Key Value ---- ----- -external help file platyPS-help.xml -schema 2.0.0 -``` - -This command retrieves metadata from a markdown file. - -### Example 2: Get metadata from a markdown string -``` -PS C:\> $Markdown = Get-Content -Path ".\docs\Get-MarkdownMetadata.md" -Raw -PS C:\> Get-MarkdownMetadata -Markdown $Markdown - -Key Value ---- ----- -external help file platyPS-help.xml -schema 2.0.0 -``` - -The first command gets the contents of a file, and stores them in the $Markdown variable. - -The second command retrieves metadata from the string in $Metadata. - -### Example 3: Get metadata from all files in a folder -``` -PS C:\> Get-MarkdownMetadata -Path ".\docs" - -Key Value ---- ----- -external help file platyPS-help.xml -schema 2.0.0 -external help file platyPS-help.xml -schema 2.0.0 -external help file platyPS-help.xml -schema 2.0.0 -external help file platyPS-help.xml -schema 2.0.0 -external help file platyPS-help.xml -schema 2.0.0 -external help file platyPS-help.xml -schema 2.0.0 -external help file platyPS-help.xml -schema 2.0.0 -external help file platyPS-help.xml -schema 2.0.0 -``` - -This command gets metadata from each of the markdown files in the .\docs folder. - -## PARAMETERS - -### -Path -Specifies an array of paths of markdown files or folders. - -```yaml -Type: String[] -Parameter Sets: FromPath -Aliases: - -Required: True -Position: Named -Default value: None -Accept pipeline input: True (ByPropertyName, ByValue) -Accept wildcard characters: True -``` - -### -Markdown -Specifies a string that contains markdown formatted text. - -```yaml -Type: String -Parameter Sets: FromMarkdownString -Aliases: - -Required: True -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### String[] -You can pipe an array of paths to this cmdlet. - -## OUTPUTS - -### Dictionary[String, String] -The cmdlet returns a **Dictionary\[String, String\]** object. -The dictionary contains key-value pairs found in the markdown metadata block. - -## NOTES - -## RELATED LINKS diff --git a/v1/docs/Merge-MarkdownHelp.md b/v1/docs/Merge-MarkdownHelp.md deleted file mode 100644 index dbb8e8cc..00000000 --- a/v1/docs/Merge-MarkdownHelp.md +++ /dev/null @@ -1,157 +0,0 @@ ---- -external help file: platyPS-help.xml -Module Name: platyPS -online version: -schema: 2.0.0 ---- - -# Merge-MarkdownHelp - -## SYNOPSIS -Merge multiple markdown versions of the same cmdlet into a single markdown file. - -## SYNTAX - -``` -Merge-MarkdownHelp [-Path] [-OutputPath] [-Encoding ] [-ExplicitApplicableIfAll] - [-Force] [[-MergeMarker] ] [] -``` - -## DESCRIPTION -Similar modules, or different versions of the same module, often contain duplicate content. - -Merge-MarkdownHelp merges the multiple markdown files into a single markdown file. -It uses the `applicable:` yaml metadata field to identify what versions or tags are applicable. -It acts on two levels: for the whole cmdlet and for individual parameters. - -The resulting markdown contains the `applicable:` tags as well as all of the content of the original markdown files. -Duplicate content is simply ignored. -Content that is unique to each file is merged using **merge markers**, followed by a comma-separated list of applicable tags. -A **merge marker** is a string of text that acts as a marker to describe the content that was merged. -The default **merge marker** text consists of three exclamation points !!! however this can be changed to any relevant text using the **-MergeMarker** flag. - -## EXAMPLES - -### Example 1 -The Test-CsPhoneBootstrap.md cmdlet is included in both Lync Server 2010 and Lync Server 2013. -Much of the content is duplicated and thus we want to have a single file for the cmdlet with unique content merged from each individual file. - -``` -PS C:\> Merge-MarkdownHelp -Path @('Lync Server 2010\Test-CsPhoneBootstrap.md', 'Lync Server 2013\Test-CsPhoneBootstrap.md') -OutputPath lync -``` - -The resulting file will be located at lync\Test-CsPhoneBootstrap.md - -## PARAMETERS - -### -Encoding -Specifies the character encoding for your external help file. -Specify a **System.Text.Encoding** object. -For more information, see [Character Encoding in the .NET Framework](https://msdn.microsoft.com/en-us/library/ms404377.aspx) in the Microsoft Developer Network. -For example, you can control Byte Order Mark (BOM) preferences. -For more information, see [Using PowerShell to write a file in UTF-8 without the BOM](http://stackoverflow.com/questions/5596982/using-powershell-to-write-a-file-in-utf-8-without-the-bom) at the Stack Overflow community. - -```yaml -Type: Encoding -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: UTF8 without BOM -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -ExplicitApplicableIfAll -Always write out full list of applicable tags. -By default cmdlets and parameters that are present in all variations don't get an application tag. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Force -Indicates that this cmdlet overwrites an existing file that has the same name. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -MergeMarker -String to be used as a merge text indicator. -Applicable tag list would be included after the marker - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 3 -Default value: '!!! ' -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -OutputPath -Specifies the path of the folder where this cmdlet creates the combined markdown help files. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: True -Position: 1 -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Path -Specifies an array of paths of markdown files or folders. -This cmdlet creates combined markdown help based on these files and folders. - -```yaml -Type: String[] -Parameter Sets: (All) -Aliases: - -Required: True -Position: 0 -Default value: None -Accept pipeline input: True (ByValue) -Accept wildcard characters: True -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### System.String[] - -## OUTPUTS - -### System.IO.FileInfo[] - -## NOTES - -## RELATED LINKS diff --git a/v1/docs/New-ExternalHelp.md b/v1/docs/New-ExternalHelp.md deleted file mode 100644 index 1490e13c..00000000 --- a/v1/docs/New-ExternalHelp.md +++ /dev/null @@ -1,241 +0,0 @@ ---- -external help file: platyPS-help.xml -Module Name: platyPS -online version: https://github.com/PowerShell/platyPS/blob/master/docs/New-ExternalHelp.md -schema: 2.0.0 ---- - -# New-ExternalHelp - -## SYNOPSIS -Creates external help file based on markdown supported by PlatyPS. - -## SYNTAX - -``` -New-ExternalHelp -Path -OutputPath [-ApplicableTag ] [-Encoding ] - [-MaxAboutWidth ] [-ErrorLogFile ] [-Force] [-ShowProgress] [] -``` - -## DESCRIPTION -The **New-ExternalHelp** cmdlet creates an external help file based on markdown help files supported by PlatyPS. -You can ship this with a module to provide help by using the **Get-Help** cmdlet. - -If the markdown files that you specify do not follow the PlatyPS [Schema](https://github.com/PowerShell/platyPS/blob/master/platyPS.schema.md), this cmdlet returns error messages. - -## EXAMPLES - -### Example 1: Create external help based on the contents of a folder -``` -PS C:\> New-ExternalHelp -Path ".\docs" -OutputPath "out\platyPS\en-US" - - Directory: D:\Working\PlatyPS\out\platyPS\en-US - - -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a---- 5/19/2016 12:32 PM 46776 platyPS-help.xml -``` - -This command creates an external help file in the specified location. -This command uses the best practice that the folder name includes the locale. - -### Example 2: Create help that uses custom encoding -``` -PS C:\> New-ExternalHelp -Path ".\docs" -OutputPath "out\PlatyPS\en-US" -Force -Encoding ([System.Text.Encoding]::Unicode) - - - Directory: D:\Working\PlatyPS\out\PlatyPS\en-US - - -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a---- 5/22/2016 6:34 PM 132942 platyPS-help.xml -``` - -This command creates an external help file in the specified location. -This command specifies the *Force* parameter, therefore, it overwrites an existing file. -The command specifies Unicode encoding for the created file. - -### Example 3: Write warnings and errors to file -``` -PS C:\> New-ExternalHelp -Path ".\docs" -OutputPath "out\platyPS\en-US" -ErrorLogFile ".\WarningsAndErrors.json" - - Directory: D:\Working\PlatyPS\out\platyPS\en-US - - -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a---- 5/19/2016 12:32 PM 46776 platyPS-help.xml -``` - -This command creates an external help file in the specified location. -This command uses the best practice that the folder name includes the locale. -This command writes the warnings and errors to the WarningsAndErrors.json file. - -## PARAMETERS - -### -OutputPath -Specifies the path of a folder where this cmdlet saves your external help file. -The folder name should end with a locale folder, as in the following example: `.\out\PlatyPS\en-US\`. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: True -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Encoding -Specifies the character encoding for your external help file. -Specify a **System.Text.Encoding** object. -For more information, see [Character Encoding in the .NET Framework](https://msdn.microsoft.com/en-us/library/ms404377.aspx) in the Microsoft Developer Network. -For example, you can control Byte Order Mark (BOM) preferences. -For more information, see [Using PowerShell to write a file in UTF-8 without the BOM](http://stackoverflow.com/questions/5596982/using-powershell-to-write-a-file-in-utf-8-without-the-bom) at the Stack Overflow community. - -```yaml -Type: Encoding -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: UTF8 without BOM -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Force -Indicates that this cmdlet overwrites an existing file that has the same name. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Path -Specifies an array of paths of markdown files or folders. -This cmdlet creates external help based on these files and folders. - -```yaml -Type: String[] -Parameter Sets: (All) -Aliases: - -Required: True -Position: Named -Default value: None -Accept pipeline input: True (ByPropertyName, ByValue) -Accept wildcard characters: True -``` - -### -ApplicableTag -Specify array of tags to use as a filter. -If cmdlet has `applicable` in the yaml metadata and none of the passed tags is -mentioned there, cmdlet would be ignored in the generated help. -Same applies to the Parameter level `applicable` yaml metadata. -If `applicable` is ommited, cmdlet or parameter would be always present. -See [design issue](https://github.com/PowerShell/platyPS/issues/273) for more details. - -```yaml -Type: String[] -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -MaxAboutWidth -Specifies the maximimum line length when generating "about" help text files. -(See New-MarkdownAboutHelp.) Other help file types are not affected by this -parameter. - -Lines inside code blocks are not wrapped at all and are not affected by the -MaxAboutWidth parameter. - -```yaml -Type: Int32 -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: 80 -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -ErrorLogFile -The path where this cmdlet will save formatted results log file. - -The path must include the location and name of the folder and file name with -the json extension. The JSON object contains three properties, Message, FilePath, -and Severity (Warning or Error). - -If this path is not provided, no log will be generated. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -ShowProgress -Display progress bars under parsing existing markdown files. - -If this is used generating of help is much slower. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### String[] -You can pipe an array of paths to this cmdlet. - -## OUTPUTS - -### System.IO.FileInfo[] -This cmdlet returns a **FileInfo[]** object for created files. - -## NOTES - -## RELATED LINKS - -[PowerShell V2 External MAML Help](https://blogs.msdn.microsoft.com/powershell/2008/12/24/powershell-v2-external-maml-help/) - -[Schema](https://github.com/PowerShell/platyPS/blob/master/platyPS.schema.md) diff --git a/v1/docs/New-ExternalHelpCab.md b/v1/docs/New-ExternalHelpCab.md deleted file mode 100644 index 44227732..00000000 --- a/v1/docs/New-ExternalHelpCab.md +++ /dev/null @@ -1,126 +0,0 @@ ---- -external help file: platyPS-help.xml -Module Name: platyPS -online version: https://github.com/PowerShell/platyPS/blob/master/docs/New-ExternalHelpCab.md -schema: 2.0.0 ---- - -# New-ExternalHelpCab - -## SYNOPSIS -Generates a .cab file. - -## SYNTAX - -``` -New-ExternalHelpCab -CabFilesFolder -LandingPagePath -OutputFolder - [-IncrementHelpVersion] [] -``` - -## DESCRIPTION -The **New-ExternalHelpCab** cmdlet generates a .cab file that contains all the non-recursive content in a folder. -This cmdlet compresses the provided files. - -We recommend that you provide as content only about_ topics and the output from the [New-ExternalHelp](New-ExternalHelp.md) cmdlet to this cmdlet. - -This cmdlet uses metadata stored in the module markdown file to name your .cab file. -This naming matches the pattern that the Windows PowerShell help system requires for use as updatable help. -This metadata is part of the module file created by using the [New-MarkdownHelp](New-MarkdownHelp.md) cmdlet with the *WithModulePage* parameter. - -This cmdlet also generates or updates an existing helpinfo.xml file. -That file provides versioning and locale details to the Windows PowerShell help system. - -## EXAMPLES - -### Example 1: Create a CAB file -``` -PS C:\> New-ExternalHelpCab -CabFilesFolder 'C:\Module\ExternalHelpContent' -LandingPagePath 'C:\Module\ModuleName.md' -OutputPath 'C:\Module\Cab\' -``` - -This commmand creates a .cab file that contains the content folder files. -The .cab file is named for updatable help based on metadata. -The command places the .cab file in the output folder. - -## PARAMETERS - -### -CabFilesFolder -Specifies the folder that contains the help content that this cmdlet packages into a .cab file. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: True -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -LandingPagePath -Specifies the full path of the Module Markdown file that contains all the metadata required to name the .cab file. -For the required metadata, run **New-MarkdownHelp** with the *WithLandingPage* parameter. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: True -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -OutputFolder -Specifies the location of the .cab file and helpinfo.xml file that this cmdlet creates. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: True -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -IncrementHelpVersion -Automatically increment the help version in the module markdown file. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### None -You cannot pipe values to this cmdlet. - -## OUTPUTS - -### None -This cmdlet does not generate output. -The cmldet saves its results in the output folder that the *OutputPath* parameter specifies. - -## NOTES - -## RELATED LINKS - -[New-ExternalHelp](New-ExternalHelp.md) -[New-MarkdownAboutHelp](New-MarkdownAboutHelp.md) diff --git a/v1/docs/New-MarkdownAboutHelp.md b/v1/docs/New-MarkdownAboutHelp.md deleted file mode 100644 index 70b82aaa..00000000 --- a/v1/docs/New-MarkdownAboutHelp.md +++ /dev/null @@ -1,111 +0,0 @@ ---- -external help file: platyPS-help.xml -Module Name: platyPS -online version: https://github.com/PowerShell/platyPS/blob/master/docs/New-MarkdownAboutHelp.md -schema: 2.0.0 ---- - -# New-MarkdownAboutHelp - -## SYNOPSIS -Generates a new About Topic MD file from template. - -## SYNTAX - -``` -New-MarkdownAboutHelp [-OutputFolder] [[-AboutName] ] [] -``` - -## DESCRIPTION -The **New-MarkdownAboutHelp** cmdlet generates a Markdown file that is prepopulated with the standard elements of an About Topic. -The cmdlet copies the template MD, renames headers and file name according to the **AboutName** parameter, -and deposits the file in the directory designated by the **OutputFoler** parameter. - -The About Topic can be converted to Txt format. -About topics must be in txt format or the PowerShell Help engine will not be able to parse the document. -Use the [New-ExternalHelp](New-ExternalHelp.md) cmdlet to convert About Topic markdown files into About Topic txt files. - -## EXAMPLES - -### Example 1 -``` -PS C:\> New-MarkdownAboutHelp -OutputFolder C:\Test -AboutName -PS C:\> Get-ChildItem C:\Test - - Directory: C:\Test - - -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a---- 7/13/2016 2:12 PM 1491 TestAboutTopic.md -``` - -Create and display file info for PowerShell About Topic Markdown File. - -### Example 2 -``` -PS C:\> New-ExternalHelp -Path C:\Test\ -OutputPath C:\Test - - - Directory: C:\Test - - -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a---- 7/13/2016 2:15 PM 1550 TestAboutTopic.txt -``` - -Create PowerShell About Topic Txt file from existing Markdown About file. - -## PARAMETERS - -### -AboutName -The name of the about topic. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 1 -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -OutputFolder -The directory to create the about topic in. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: True -Position: 0 -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### None - -## OUTPUTS - -### System.Object -This cmdlet returns a object for created files. - -## NOTES -The about topics will need to be added to a cab file to leverage updatable help. - -## RELATED LINKS - -[New-ExternalHelp](New-ExternalHelp.md) - -[New-ExternalHelpCab](New-ExternalHelpCab.md) diff --git a/v1/docs/New-MarkdownHelp.md b/v1/docs/New-MarkdownHelp.md deleted file mode 100644 index e83e3275..00000000 --- a/v1/docs/New-MarkdownHelp.md +++ /dev/null @@ -1,513 +0,0 @@ ---- -external help file: platyPS-help.xml -Module Name: platyPS -online version: https://github.com/PowerShell/platyPS/blob/master/docs/New-MarkdownHelp.md -schema: 2.0.0 ---- - -# New-MarkdownHelp - -## SYNOPSIS -Creates help in markdown format. - -## SYNTAX - -### FromModule -``` -New-MarkdownHelp -Module [-Session ] [-Force] [-AlphabeticParamsOrder] - [-Metadata ] -OutputFolder [-NoMetadata] [-UseFullTypeName] [-Encoding ] - [-WithModulePage] [-ModulePagePath ] [-Locale ] [-HelpVersion ] [-FwLink ] - [-ExcludeDontShow] [] -``` - -### FromCommand -``` -New-MarkdownHelp -Command [-Session ] [-Force] [-AlphabeticParamsOrder] - [-Metadata ] [-OnlineVersionUrl ] -OutputFolder [-NoMetadata] [-UseFullTypeName] - [-Encoding ] [-ExcludeDontShow] [] -``` - -### FromMaml -``` -New-MarkdownHelp -MamlFile [-ConvertNotesToList] [-ConvertDoubleDashLists] [-Force] - [-AlphabeticParamsOrder] [-Metadata ] -OutputFolder [-NoMetadata] [-UseFullTypeName] - [-Encoding ] [-WithModulePage] [-ModulePagePath ] [-Locale ] [-HelpVersion ] - [-FwLink ] [-ModuleName ] [-ModuleGuid ] [-ExcludeDontShow] [] -``` - -## DESCRIPTION -The **New-MarkdownHelp** cmdlet creates help in markdown format based on a module, a command, or a file in Microsoft Assistance Markup Language (MAML) format. - -## EXAMPLES - -### Example 1: Create help from a command -``` -PS C:\> function Command03 {param([string]$Value)} -PS C:\> New-MarkdownHelp -Command "Command03" -OutputFolder ".\docs" - - - Directory: D:\Working\docs - - -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a---- 5/22/2016 6:53 PM 664 Command03.md -``` - -The first command creates a function named Command03 by using standard Windows PowerShell syntax. - -The second command creates help for that stub function in the .\docs folder. - -### Example 2: Create help from a module -``` -PS C:\> Import-Module -Module "PlatyPS" -PS C:\> New-MarkdownHelp -Module "PlatyPS" -OutputFolder ".\docs" -Force - - - Directory: D:\Working\PlatyPS\docs - - -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a---- 5/22/2016 6:54 PM 1496 Get-HelpPreview.md --a---- 5/22/2016 6:54 PM 3208 Get-MarkdownMetadata.md --a---- 5/22/2016 6:54 PM 3059 New-ExternalHelp.md --a---- 5/22/2016 6:54 PM 2702 New-ExternalHelpCab.md --a---- 5/22/2016 6:54 PM 6234 New-MarkdownHelp.md --a---- 5/22/2016 6:54 PM 2346 Update-MarkdownHelp.md --a---- 5/22/2016 6:54 PM 1633 Update-MarkdownHelpModule.md --a---- 5/22/2016 6:54 PM 1630 Update-MarkdownHelpSchema.md -``` - -The first command loads the PlatyPS module into the current session by using the **Import-Module** cmdlet. - -The second command creates help for all the cmdlets in the PlatyPS module. -It stores them in the .\docs folder. -This command specifies the *Force* parameter. -Therefore, it overwrites existing help markdown files that have the same name. - -### Example 3: Create help from an existing MAML file -``` -PS C:\> New-MarkdownHelp -OutputFolder "D:\PSReadline\docs" -MamlFile 'C:\Program Files\WindowsPowerShell\Modules\PSReadline\1.1\en-US\Microsoft.PowerShell.PSReadline.dll-help.xml' - - Directory: D:\PSReadline\docs - - -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a---- 5/22/2016 6:56 PM 7443 Get-PSReadlineKeyHandler.md --a---- 5/22/2016 6:56 PM 3586 Get-PSReadlineOption.md --a---- 5/22/2016 6:56 PM 1549 Remove-PSReadlineKeyHandler.md --a---- 5/22/2016 6:56 PM 5947 Set-PSReadlineKeyHandler.md --a---- 5/22/2016 6:56 PM 15320 Set-PSReadlineOption.md -``` - -This command creates help in markdown format for the specified help MAML file. -You do not have to load the module, as in the previous example. -If the module is already loaded, this command creates help based on the MAML file, not on the currently installed module. - -### Example 4: Create help from an existing MAML file for use in a CAB file -``` -PS C:\> New-MarkdownHelp -OutputFolder "D:\PSReadline\docs" -MamlFile 'C:\Program Files\WindowsPowerShell\Modules\PSReadline\1.1\en-US\Microsoft.PowerShell.PSReadline.dll-help.xml' -WithModulePage -Force -ModuleName "PSReadLine" - - - Directory: D:\PSReadline\docs - - -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a---- 5/22/2016 6:59 PM 7443 Get-PSReadlineKeyHandler.md --a---- 5/22/2016 6:59 PM 3586 Get-PSReadlineOption.md --a---- 5/22/2016 6:59 PM 1549 Remove-PSReadlineKeyHandler.md --a---- 5/22/2016 6:59 PM 5947 Set-PSReadlineKeyHandler.md --a---- 5/22/2016 6:59 PM 15320 Set-PSReadlineOption.md --a---- 5/22/2016 6:59 PM 942 PSReadLine.md -``` - -This command creates help in markdown format for the specified help MAML file, as in the previous example. -This command also specifies the *WithModulePage* parameter and the *ModuleName* parameter. -The command creates a file named PSReadLine.md that contains links to the other markdown files in this module and metadata that can be used to create .cab files. - -## PARAMETERS - -### -Command -Specifies the name of a command in your current session. -This can be any command supported by Windows PowerShell help, such as a cmdlet or a function. - -```yaml -Type: String[] -Parameter Sets: FromCommand -Aliases: - -Required: True -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Encoding -Specifies the character encoding for your markdown help files. -Specify a **System.Text.Encoding** object. -For more information, see [Character Encoding in the .NET Framework](https://msdn.microsoft.com/en-us/library/ms404377.aspx) in the Microsoft Developer Network. -For example, you can control Byte Order Mark (BOM) preferences. -For more information, see [Using PowerShell to write a file in UTF-8 without the BOM](http://stackoverflow.com/questions/5596982/using-powershell-to-write-a-file-in-utf-8-without-the-bom) at the Stack Overflow community. - -```yaml -Type: Encoding -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: UTF8 without BOM -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Force -Indicates that this cmdlet overwrites existing files that have the same names. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -FwLink -Specifies the forward link for the module page. -This value is required for .cab file creation. -This value is used as markdown header metadata in the module page. - -```yaml -Type: String -Parameter Sets: FromModule, FromMaml -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -HelpVersion -Specifies the version of your help. -This value is required for .cab file creation. -This value is used as markdown header metadata in the module page. - -```yaml -Type: String -Parameter Sets: FromModule, FromMaml -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Locale -Specifies the locale of your help. -This value is required for .cab file creation. -This value is used as markdown header metadata in the module page. - -```yaml -Type: String -Parameter Sets: FromModule, FromMaml -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -MamlFile -Specifies an array of paths path of MAML .xml help files. - -```yaml -Type: String[] -Parameter Sets: FromMaml -Aliases: - -Required: True -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Metadata -Specifies metadata that this cmdlet includes in the help markdown files as a hash table of string-to-sting key-value pairs. -This cmdlet writes the metadata in the header of each markdown help file. - -The **New-ExternalHelp** cmdlet does not use this metadata. -External tools can use this metadata. - -```yaml -Type: Hashtable -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Module -Specifies an array of names of modules for which this cmdlet creates help in markdown format. - -```yaml -Type: String[] -Parameter Sets: FromModule -Aliases: - -Required: True -Position: Named -Default value: None -Accept pipeline input: True (ByValue) -Accept wildcard characters: False -``` - -### -ModuleGuid -Specifies the GUID of the module of your help. -This value is required for .cab file creation. -This value is used as markdown header metadata in the module page. - -```yaml -Type: String -Parameter Sets: FromMaml -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -ModuleName -Specifies the name of the module of your help. -This value is required for .cab file creation. -This value is used as markdown header metadata in the module page. - -```yaml -Type: String -Parameter Sets: FromMaml -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -NoMetadata -Indicates that this cmdlet does not write any metadata in the generated markdown. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -OnlineVersionUrl -Specifies the URL where the updatable help function downloads updated help. -If you do not specify a value, the cmdlet uses an empty string. - -```yaml -Type: String -Parameter Sets: FromCommand -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -OutputFolder -Specifies the path of the folder where this cmdlet creates the markdown help files. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: True -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -WithModulePage -Indicates that this cmdlet creates a module page in the output folder. -This file has the name that the *ModuleName* parameter specifies. -If you did not specify that parameter, the cmdlet supplies the default name MamlModule. -You can overwrite this setting by using *ModulePagePath* which allows you to define different path for module page - -```yaml -Type: SwitchParameter -Parameter Sets: FromModule, FromMaml -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -ConvertNotesToList -Indicates that this cmldet formats multiple paragraph items in the **NOTES** section as single list items. -This output follows TechNet formatting. - -```yaml -Type: SwitchParameter -Parameter Sets: FromMaml -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -ConvertDoubleDashLists -Indicates that this cmldet converts double-hyphen list bullets into single-hyphen bullets. -Double-hyphen lists are common in Windows PowerShell documentation. -Markdown accepts single-hyphens for lists. - -```yaml -Type: SwitchParameter -Parameter Sets: FromMaml -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -AlphabeticParamsOrder -Order parameters alphabetically by name in PARAMETERS section. -There are 5 exceptions: -Confirm, -WhatIf, -IncludeTotalCount, -Skip, and -First parameters will be the last. -These parameters are common and hence have well-defined behavior. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -UseFullTypeName -Indicates that the target document will use a full type name instead of a short name for parameters. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Session -Provides support for remote commands. -Pass the session that you used to create the commands with `Import-PSSession`. -This is required to get accurate parameters metadata from the remote session. - -```yaml -Type: PSSession -Parameter Sets: FromModule, FromCommand -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -ModulePagePath -When *WithModule* parameter is used by default it puts .md file in same location as all other docs. With this parameter you can specify new name/location providing better placement options. - -```yaml -Type: String -Parameter Sets: FromModule, FromMaml -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -ExcludeDontShow -Exclude the parameters marked with `DontShow` in the parameter attribute from the help content. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### String[] -You can pipe module names to this cmdlet. -These are the modules from which this cmdlet creates help markdown. - -## OUTPUTS - -### System.IO.FileInfo[] -This cmdlet returns a **FileInfo[]** object for created files. - -## NOTES - -## RELATED LINKS - -[Character Encoding in the .NET Framework](https://msdn.microsoft.com/en-us/library/ms404377.aspx) - -[Using PowerShell to write a file in UTF-8 without the BOM](http://stackoverflow.com/questions/5596982/using-powershell-to-write-a-file-in-utf-8-without-the-bom) diff --git a/v1/docs/New-YamlHelp.md b/v1/docs/New-YamlHelp.md deleted file mode 100644 index 019e300f..00000000 --- a/v1/docs/New-YamlHelp.md +++ /dev/null @@ -1,153 +0,0 @@ ---- -external help file: platyPS-help.xml -Module Name: platyPS -online version: https://github.com/PowerShell/platyPS/blob/master/docs/New-YamlHelp.md -schema: 2.0.0 ---- - -# New-YamlHelp - -## SYNOPSIS -Converts Markdown help into YAML to be read easily by external tools - -## SYNTAX - -``` -New-YamlHelp [-Path] -OutputFolder [-Encoding ] [-Force] [] -``` - -## DESCRIPTION -The **New-YamlHelp** cmdlet works similarly to the **New-ExternalHelp** cmdlet but rather than creating a MAML file to support **Get-Help**, it creates a set of YAML files that can be read by external tools to provide custom rendering of help pages. - -## EXAMPLES - -### Example 1: Create YAML files -``` -PS C:\> New-YamlHelp -Path .\docs -OutputFolder .\out\yaml - - Directory: D:\Working\PlatyPS\out\yaml - - -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a---- 6/15/2017 11:13 AM 2337 Get-HelpPreview.yml --a---- 6/15/2017 11:13 AM 3502 Get-MarkdownMetadata.yml --a---- 6/15/2017 11:13 AM 4143 New-ExternalHelp.yml --a---- 6/15/2017 11:13 AM 3082 New-ExternalHelpCab.yml --a---- 6/15/2017 11:13 AM 2581 New-MarkdownAboutHelp.yml --a---- 6/15/2017 11:13 AM 12356 New-MarkdownHelp.yml --a---- 6/15/2017 11:13 AM 1681 New-YamlHelp.yml --a---- 6/15/2017 11:13 AM 5053 Update-MarkdownHelp.yml --a---- 6/15/2017 11:13 AM 4661 Update-MarkdownHelpModule.yml --a---- 6/15/2017 11:13 AM 3350 Update-MarkdownHelpSchema.yml -``` - -This creates one YAML file for each cmdlet so external tools can read the structured data for each cmdlet. - -### Example 2: Create YAML files with specific encoding -``` -PS C:\> New-YamlHelp -Path .\docs -OutputFolder .\out\yaml -Force -Encoding ([System.Text.Encoding]::Unicode) - - Directory: D:\Working\PlatyPS\out\yaml - - -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a---- 6/15/2017 11:13 AM 2337 Get-HelpPreview.yml --a---- 6/15/2017 11:13 AM 3502 Get-MarkdownMetadata.yml --a---- 6/15/2017 11:13 AM 4143 New-ExternalHelp.yml --a---- 6/15/2017 11:13 AM 3082 New-ExternalHelpCab.yml --a---- 6/15/2017 11:13 AM 2581 New-MarkdownAboutHelp.yml --a---- 6/15/2017 11:13 AM 12356 New-MarkdownHelp.yml --a---- 6/15/2017 11:13 AM 1681 New-YamlHelp.yml --a---- 6/15/2017 11:13 AM 5053 Update-MarkdownHelp.yml --a---- 6/15/2017 11:13 AM 4661 Update-MarkdownHelpModule.yml --a---- 6/15/2017 11:13 AM 3350 Update-MarkdownHelpSchema.yml -``` - -This will both read and write the files in the specified -Encoding. -The -Force parameter will overwrite files that already exist. - -## PARAMETERS - -### -Encoding -Specifies the character encoding for your external help file. -Specify a **System.Text.Encoding** object. -For more information, see [Character Encoding in the .NET Framework](https://msdn.microsoft.com/en-us/library/ms404377.aspx) in the Microsoft Developer Network. -For example, you can control Byte Order Mark (BOM) preferences. -For more information, see [Using PowerShell to write a file in UTF-8 without the BOM](http://stackoverflow.com/questions/5596982/using-powershell-to-write-a-file-in-utf-8-without-the-bom) at the Stack Overflow community. - -```yaml -Type: Encoding -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Force -Indicates that this cmdlet overwrites an existing file that has the same name. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Path -Specifies an array of paths of markdown files or folders. -This cmdlet creates external help based on these files and folders. - -```yaml -Type: String[] -Parameter Sets: (All) -Aliases: - -Required: True -Position: 1 -Default value: None -Accept pipeline input: True (ByPropertyName, ByValue) -Accept wildcard characters: False -``` - -### -OutputFolder -Specifies the folder to create the YAML files in - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: True -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### System.String[] -You can pipe an array of paths to this cmdlet. - -## OUTPUTS - -### System.IO.FileInfo[] -This cmdlet returns a **FileInfo[]** object for created files. - -## NOTES - -## RELATED LINKS diff --git a/v1/docs/Update-MarkdownHelp.md b/v1/docs/Update-MarkdownHelp.md deleted file mode 100644 index ea3b755f..00000000 --- a/v1/docs/Update-MarkdownHelp.md +++ /dev/null @@ -1,256 +0,0 @@ ---- -external help file: platyPS-help.xml -Module Name: platyPS -online version: https://github.com/PowerShell/platyPS/blob/master/docs/Update-MarkdownHelp.md -schema: 2.0.0 ---- - -# Update-MarkdownHelp - -## SYNOPSIS -Update PlatyPS markdown help files. - -## SYNTAX - -``` -Update-MarkdownHelp [-Path] [[-Encoding] ] [[-LogPath] ] [-LogAppend] - [-AlphabeticParamsOrder] [-UseFullTypeName] [-UpdateInputOutput] [-Force] [-Session ] - [-ExcludeDontShow] [] -``` - -## DESCRIPTION -The **Update-MarkdownHelp** cmdlet updates PlatyPS markdown help files without completely replacing the content of the files. - -Some parameter attributes change over time. -For instance, parameter sets, types, default value, and required. -This cmdlet updates markdown help to reflect those changes. -It also adds placeholder text to the markdown file for any new parameter. - -To propagate changes to your markdown help files, do the following: - -- Load the new version of the module into your Windows PowerShell session. -- Run the **Update-MarkdownHelp** cmdlet to update the files. -- Check new parameters metadata in the markdown files. - -## EXAMPLES - -### Example 1: Update all files in a folder -``` -PS C:\> Update-MarkdownHelp -Path ".\docs" - - Directory: D:\working\PlatyPS\docs - - -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a---- 5/22/2016 6:54 PM 1496 Get-HelpPreview.md --a---- 5/22/2016 6:54 PM 3208 Get-MarkdownMetadata.md --a---- 5/22/2016 6:54 PM 3059 New-ExternalHelp.md --a---- 5/22/2016 6:54 PM 2702 New-ExternalHelpCab.md --a---- 5/22/2016 6:54 PM 6234 New-MarkdownHelp.md --a---- 5/22/2016 6:54 PM 2346 Update-MarkdownHelp.md --a---- 5/22/2016 6:54 PM 1633 Update-MarkdownHelpModule.md --a---- 5/22/2016 6:54 PM 1630 Update-MarkdownHelpSchema.md -``` - -This command updates all markdown help files in the specified path to match the current cmdlets. - -### Example 2: Update one file and capture log -``` -PS C:\> Update-MarkdownHelp -Path ".\docs\Update-MarkdownHelp.md" -LogPath ".\markdown.log" - - Directory: D:\Working\PlatyPS\docs - - -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a---- 5/22/2016 8:20 PM 9993 New-MarkdownHelp.md -``` - -This command updates a markdown help file. -It writes log information to the markdown.log file. - -## PARAMETERS - -### -Encoding -Specifies the character encoding for your markdown help files. -Specify a **System.Text.Encoding** object. -For more information, see [Character Encoding in the .NET Framework](https://msdn.microsoft.com/en-us/library/ms404377.aspx) in the Microsoft Developer Network. -For example, you can control Byte Order Mark (BOM) preferences. -For more information, see [Using PowerShell to write a file in UTF-8 without the BOM](http://stackoverflow.com/questions/5596982/using-powershell-to-write-a-file-in-utf-8-without-the-bom) at the Stack Overflow community. - -```yaml -Type: Encoding -Parameter Sets: (All) -Aliases: - -Required: False -Position: 1 -Default value: UTF8 without BOM -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -LogAppend -Indicates that this cmdlet appends information to the log instead overwriting it. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -LogPath -Specifies a file path for log information. -The cmdlet writes the VERBOSE stream to the log. -If you specify the *Verbose* parameter, this cmdlet also writes that information to the console. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 2 -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Path -Specifies an array of paths of markdown files and folders to update. - -```yaml -Type: String[] -Parameter Sets: (All) -Aliases: - -Required: True -Position: 0 -Default value: None -Accept pipeline input: True (ByValue) -Accept wildcard characters: True -``` - -### -AlphabeticParamsOrder -Order parameters alphabetically by name in PARAMETERS section. -There are 5 exceptions: -Confirm, -WhatIf, -IncludeTotalCount, -Skip, and -First parameters will be the last. -These parameters are common and hence have well-defined behavior. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -UseFullTypeName -Indicates that the target document will use a full type name instead of a short name for parameters. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Session -Provides support for remote commands. -Pass the session that you used to create the commands with `Import-PSSession`. -This is required to get accurate parameters metadata from the remote session. - -```yaml -Type: PSSession -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -UpdateInputOutput -Refreshes the Input and Output section to reflect the current state of the cmdlet. WARNING: this parameter will remove any manual additions to these sections. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Force -Remove help files that no longer exists within sessions (for example if function was deleted) - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -ExcludeDontShow -Exclude the parameters marked with `DontShow` in the parameter attribute from the help content. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### String[] -You can pipe an array of paths to this cmdlet. - -## OUTPUTS - -### System.IO.FileInfo[] -This cmdlet returns a **FileInfo[]** object for updated files. - -## NOTES -The module for which you want to update the help should first be imported from the location containing the previous version of the help. -If this condition is not met, the parameter order will be alphabetical in the updated help, even if the parameter *AlphabeticParamsOrder* has not been used. - -## RELATED LINKS - -[Character Encoding in the .NET Framework](https://msdn.microsoft.com/en-us/library/ms404377.aspx) - -[Using PowerShell to write a file in UTF-8 without the BOM](http://stackoverflow.com/questions/5596982/using-powershell-to-write-a-file-in-utf-8-without-the-bom) diff --git a/v1/docs/Update-MarkdownHelpModule.md b/v1/docs/Update-MarkdownHelpModule.md deleted file mode 100644 index 02791a27..00000000 --- a/v1/docs/Update-MarkdownHelpModule.md +++ /dev/null @@ -1,263 +0,0 @@ ---- -external help file: platyPS-help.xml -Module Name: platyPS -online version: https://github.com/PowerShell/platyPS/blob/master/docs/Update-MarkdownHelpModule.md -schema: 2.0.0 ---- - -# Update-MarkdownHelpModule - -## SYNOPSIS -Update all files in a markdown help module folder. - -## SYNTAX - -``` -Update-MarkdownHelpModule [-Path] [[-Encoding] ] [-RefreshModulePage] - [-ModulePagePath ] [[-LogPath] ] [-LogAppend] [-AlphabeticParamsOrder] [-UseFullTypeName] - [-UpdateInputOutput] [-Force] [-Session ] [-ExcludeDontShow] [] -``` - -## DESCRIPTION -The **Update-MarkdownHelpModule** cmdlet updates existing help markdown files and creates markdown files for new cmdlets in a module. -This cmdlet combines functionality of the [Update-MarkdownHelp](Update-MarkdownHelp.md) and [New-MarkdownHelp](New-MarkdownHelp.md) cmdlets to perform a bulk update. - -## EXAMPLES - -### Example 1: Update a markdown help module -``` -PS C:\> Update-MarkdownHelpModule -Path ".\docs" - - Directory: D:\Working\PlatyPS\docs - - -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a---- 5/22/2016 6:54 PM 1496 Get-HelpPreview.md --a---- 5/22/2016 6:54 PM 3208 Get-MarkdownMetadata.md --a---- 5/22/2016 6:54 PM 3059 New-ExternalHelp.md --a---- 5/22/2016 6:54 PM 2702 New-ExternalHelpCab.md --a---- 5/22/2016 6:54 PM 6234 New-MarkdownHelp.md --a---- 5/22/2016 6:54 PM 2346 Update-MarkdownHelp.md --a---- 5/22/2016 6:54 PM 1633 Update-MarkdownHelpModule.md --a---- 5/22/2016 6:54 PM 1630 Update-MarkdownHelpSchema.md -``` - -This command updates all the files in the specified folder based on the cmdlets as loaded into your current session. -The command creates markdown help topics for any cmdlets that are not already included in the .\docs folder. - -## PARAMETERS - -### -Encoding -Specifies the character encoding for your markdown help files. -Specify a **System.Text.Encoding** object. -For more information, see [Character Encoding in the .NET Framework](https://msdn.microsoft.com/en-us/library/ms404377.aspx) in the Microsoft Developer Network. -For example, you can control Byte Order Mark (BOM) preferences. -For more information, see [Using PowerShell to write a file in UTF-8 without the BOM](http://stackoverflow.com/questions/5596982/using-powershell-to-write-a-file-in-utf-8-without-the-bom) at the Stack Overflow community. - -```yaml -Type: Encoding -Parameter Sets: (All) -Aliases: - -Required: False -Position: 1 -Default value: UTF8 without BOM -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -LogAppend -Indicates that this cmdlet appends information to the log instead overwriting it. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -LogPath -Specifies a file path for log information. -The cmdlet writes the VERBOSE stream to the log. -If you specify the *Verbose* parameter, this cmdlet also writes that information to the console. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 2 -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Path -Specifies an array of paths of markdown folders to update. -The folder must contain a module page from which this cmdlet can get the module name. - -```yaml -Type: String[] -Parameter Sets: (All) -Aliases: - -Required: True -Position: 0 -Default value: None -Accept pipeline input: True (ByValue) -Accept wildcard characters: True -``` - -### -RefreshModulePage -Update module page when updating the help module. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -AlphabeticParamsOrder -Order parameters alphabetically by name in PARAMETERS section. -There are 5 exceptions: -Confirm, -WhatIf, -IncludeTotalCount, -Skip, and -First parameters will be the last. -These parameters are common and hence have well-defined behavior. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Session -Provides support for remote commands. -Pass the session that you used to create the commands with `Import-PSSession`. -This is required to get accurate parameters metadata from the remote session. - -```yaml -Type: PSSession -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -UseFullTypeName -Indicates that the target document will use a full type name instead of a short name for parameters. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -UpdateInputOutput -Refreshes the Input and Output sections to reflect the current state of the cmdlet. WARNING: this parameter will remove any manual additions to these sections. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -ModulePagePath -When -RefreshModulePage is used by default it puts .md file in same location as all other docs. With this parameter you can specify new name/location providing better placement options. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Force -Remove help files that no longer exists within sessions (for example if function was deleted) - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -ExcludeDontShow -Exclude the parameters marked with `DontShow` in the parameter attribute from the help content. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### System.String[] -You can pipe an array of paths to this cmdlet. - -## OUTPUTS - -### System.IO.FileInfo[] -This cmdlet returns a **FileInfo[]** object for updated and new files. - -## NOTES -The module for which you want to update the help should first be imported from the location containing the previous version of the help. - If this condition is not met, the parameter order will be alphabetical in the updated help, even if the parameter *AlphabeticParamsOrder* has not been used. - -## RELATED LINKS - -[Character Encoding in the .NET Framework](https://msdn.microsoft.com/en-us/library/ms404377.aspx) - -[Using PowerShell to write a file in UTF-8 without the BOM](http://stackoverflow.com/questions/5596982/using-powershell-to-write-a-file-in-utf-8-without-the-bom) diff --git a/v1/docs/about_platyPS.md b/v1/docs/about_platyPS.md deleted file mode 100644 index 397ddea4..00000000 --- a/v1/docs/about_platyPS.md +++ /dev/null @@ -1,18 +0,0 @@ -# platyPS -## about_platyPS - -# SHORT DESCRIPTION -Write PowerShell External Help in Markdown. - -# LONG DESCRIPTION - -PlatyPS provides a way to - -- Write PowerShell External Help in Markdown -- Generate markdown help (example) for your existing modules -- Keep markdown help up-to-date with your code - -Markdown help docs can be generated from old external help files (also known as MAML-xml help), -the command objects (reflection), or both. - -PlatyPS can also generate cab files for Update-Help. diff --git a/v1/src/Markdown.MAML/Markdown.MAML.csproj b/v1/src/Markdown.MAML/Markdown.MAML.csproj deleted file mode 100644 index d11d7b28..00000000 --- a/v1/src/Markdown.MAML/Markdown.MAML.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - netstandard1.6;net451 - - - true - - - - - - - - - diff --git a/v1/src/Markdown.MAML/Model/MAML/MamlCodeBlock.cs b/v1/src/Markdown.MAML/Model/MAML/MamlCodeBlock.cs deleted file mode 100644 index d8dc77c3..00000000 --- a/v1/src/Markdown.MAML/Model/MAML/MamlCodeBlock.cs +++ /dev/null @@ -1,37 +0,0 @@ -namespace Markdown.MAML.Model.MAML -{ - /// - /// A section of code such as PowerShell commands or command output. - /// - public sealed class MamlCodeBlock - { - public MamlCodeBlock(string text, string languageMoniker = null) - { - Text = text; - LanguageMoniker = languageMoniker ?? string.Empty; - } - - /// - /// An optional language or info-string. If no language string is suppled plain text is assumed. - /// For more information see: http://spec.commonmark.org/0.28/#info-string - /// - public string LanguageMoniker { get; private set; } - - /// - /// The text of the code block. - /// - public string Text { get; private set; } - - /// - /// Serves as a hash function for a object. - /// - /// A hash code for this instance that is suitable for use in hashing algorithms and data structures such as a - /// hash table. - public override int GetHashCode() - { - return - (Text == null ? 679 : Text.GetHashCode()) ^ - (LanguageMoniker == null ? 765679 : LanguageMoniker.GetHashCode()); - } - } -} diff --git a/v1/src/Markdown.MAML/Model/MAML/MamlCommand.cs b/v1/src/Markdown.MAML/Model/MAML/MamlCommand.cs deleted file mode 100644 index 3cec6a68..00000000 --- a/v1/src/Markdown.MAML/Model/MAML/MamlCommand.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System.Collections.Generic; -using Markdown.MAML.Model.Markdown; - -namespace Markdown.MAML.Model.MAML -{ - public class MamlCommand - { - public SourceExtent Extent { get; set; } - - public string Name { get; set; } - - public SectionBody Synopsis { get; set; } - - public SectionBody Description { get; set; } - - public List Inputs - { - get { return _inputs; } - } - - public List Outputs - { - get { return _outputs; } - } - - public List Parameters - { - get { return _parameters; } - } - - public SectionBody Notes { get; set; } - - public bool IsWorkflow { get; set; } - - public bool SupportCommonParameters { get; set; } - - public string ModuleName { get; set; } - - public List Examples - { - get { return _examples; } - } - - public List Links - { - get { return _links; } - } - - public List Syntax - { - get { return _syntax; } - } - - private List _parameters = new List(); - - private List _outputs = new List(); - - private List _inputs = new List(); - - private List _examples = new List(); - - private List _links = new List(); - - private List _syntax = new List(); - - public MamlCommand() - { - // this is the default most often then not - this.SupportCommonParameters = true; - } - } -} diff --git a/v1/src/Markdown.MAML/Model/MAML/MamlExample.cs b/v1/src/Markdown.MAML/Model/MAML/MamlExample.cs deleted file mode 100644 index b4e7cc44..00000000 --- a/v1/src/Markdown.MAML/Model/MAML/MamlExample.cs +++ /dev/null @@ -1,39 +0,0 @@ -using Markdown.MAML.Model.Markdown; - -namespace Markdown.MAML.Model.MAML -{ - public class MamlExample - { - public string Title { get; set; } - public MamlCodeBlock[] Code { get; set; } - public string Remarks { get; set; } - public string Introduction { get; set; } - - /// - /// Additional options that determine how the section will be formated when rendering markdown. - /// - public SectionFormatOption FormatOption { get; set; } - - /// - /// Serves as a hash function for a object. - /// Ignores the FormatOption field. - /// - /// A hash code for this instance that is suitable for use in hashing algorithms and data structures such as a - /// hash table. - public override int GetHashCode() - { - int hash = 1; - if (Code != null) - { - foreach (var codeBlock in Code) { - hash ^= codeBlock.GetHashCode(); - } - } - return - hash ^ - (Title == null ? 123 : Title.GetHashCode()) ^ - (Remarks == null ? 12345 : Remarks.GetHashCode()) ^ - (Introduction == null ? 123457 : Introduction.GetHashCode()); - } - } -} diff --git a/v1/src/Markdown.MAML/Model/MAML/MamlInputOutput.cs b/v1/src/Markdown.MAML/Model/MAML/MamlInputOutput.cs deleted file mode 100644 index 50abf8ef..00000000 --- a/v1/src/Markdown.MAML/Model/MAML/MamlInputOutput.cs +++ /dev/null @@ -1,34 +0,0 @@ -using Markdown.MAML.Model.Markdown; -using System; - -namespace Markdown.MAML.Model.MAML -{ - /// - /// This class represent Input and Output properties for MAML. - /// - public class MamlInputOutput : IEquatable - { - public string TypeName { get; set; } - public string Description { get; set; } - - /// - /// Additional options that determine how the section will be formated when rendering markdown. - /// - public SectionFormatOption FormatOption { get; set; } - - bool IEquatable.Equals(MamlInputOutput other) - { - if (!StringComparer.OrdinalIgnoreCase.Equals(other.TypeName, this.TypeName)) - { - return false; - } - - if (!StringComparer.OrdinalIgnoreCase.Equals(other.Description, this.Description)) - { - return false; - } - - return true; - } - } -} diff --git a/v1/src/Markdown.MAML/Model/MAML/MamlLink.cs b/v1/src/Markdown.MAML/Model/MAML/MamlLink.cs deleted file mode 100644 index fb5104b3..00000000 --- a/v1/src/Markdown.MAML/Model/MAML/MamlLink.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Markdown.MAML.Model.MAML -{ - /// - /// This class represents the related links properties for MAML - /// - public class MamlLink : IEquatable - { - /// - /// This is a workaround for PreserveFormatting - /// So we can store a block of texts that suppose to represent links - /// without parsing them - /// - public bool IsSimplifiedTextLink { get; private set; } - - public string LinkName { get; set; } - public string LinkUri { get; set; } - - public MamlLink() : this(false) { } - - public MamlLink(bool isSimplifiedTextLink) - { - this.IsSimplifiedTextLink = isSimplifiedTextLink; - } - - bool IEquatable.Equals(MamlLink other) - { - if (!StringComparer.OrdinalIgnoreCase.Equals(other.LinkName, this.LinkName)) - { - return false; - } - - if (!StringComparer.OrdinalIgnoreCase.Equals(other.LinkUri, this.LinkUri)) - { - return false; - } - - return true; - } - } -} diff --git a/v1/src/Markdown.MAML/Model/MAML/MamlParameter.cs b/v1/src/Markdown.MAML/Model/MAML/MamlParameter.cs deleted file mode 100644 index 92560137..00000000 --- a/v1/src/Markdown.MAML/Model/MAML/MamlParameter.cs +++ /dev/null @@ -1,109 +0,0 @@ -using System.Collections.Generic; -using Markdown.MAML.Model.Markdown; -using System; -using System.Linq; - -namespace Markdown.MAML.Model.MAML -{ - public class MamlParameter - { - public SourceExtent Extent { get; set; } - - /// - /// Additional options that determine how the section will be formated when rendering markdown. - /// - public SectionFormatOption FormatOption { get; set; } - - public string Type { get; set; } - - public string FullType { get; set; } - - public string Name { get; set; } - - public bool Required { get; set; } - - public string Description { get; set; } - - public string DefaultValue { get; set; } - - public bool VariableLength { get; set; } - - /// - /// Corresponds to "Accept wildcard characters" - /// - public bool Globbing { get; set; } - - public string PipelineInput { get; set; } - - public string Position { get; set; } - - public string[] Aliases { get; set; } - - public string[] Applicable { get; set; } - - public bool ValueRequired { get; set; } - - public bool ValueVariableLength { get; set; } - - /// - /// This string is used only in schema version 1.0.0 internal processing - /// - internal string AttributesMetadata { get; set; } - - public List ParameterValueGroup - { - get { return _parameterValueGroup; } - } - - private readonly List _parameterValueGroup = new List(); - - - public MamlParameter() - { - VariableLength = true; - ValueVariableLength = false; - Globbing = false; - PipelineInput = "false"; - Position = "Named"; - Aliases = new string[] {}; - } - - public MamlParameter Clone() - { - return (MamlParameter)this.MemberwiseClone(); - } - - public bool IsMetadataEqual(MamlParameter other) - { - return StringComparer.OrdinalIgnoreCase.Equals(this.Name, other.Name) && - this.Required == other.Required && - StringComparer.OrdinalIgnoreCase.Equals(this.Position, other.Position) && - StringComparer.OrdinalIgnoreCase.Equals(this.PipelineInput, other.PipelineInput) && - this.Globbing == other.Globbing; - } - - public bool IsSwitchParameter() - { - return StringComparer.OrdinalIgnoreCase.Equals(this.Type, "SwitchParameter") || - StringComparer.OrdinalIgnoreCase.Equals(this.Type, "switch"); - } - - public bool IsNamed() - { - return string.IsNullOrWhiteSpace(this.Position) || - StringComparer.OrdinalIgnoreCase.Equals(this.Position, "Named"); - } - - public bool IsApplicable(string[] applicableTag) - { - if (applicableTag != null && this.Applicable != null) - { - // applicable if intersect is not empty - return applicableTag.Intersect(this.Applicable, StringComparer.OrdinalIgnoreCase).Any(); - } - - // if one is null then it's applicable - return true; - } - } -} \ No newline at end of file diff --git a/v1/src/Markdown.MAML/Model/MAML/MamlSyntax.cs b/v1/src/Markdown.MAML/Model/MAML/MamlSyntax.cs deleted file mode 100644 index 450b182e..00000000 --- a/v1/src/Markdown.MAML/Model/MAML/MamlSyntax.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Collections.Generic; - -namespace Markdown.MAML.Model.MAML -{ - public class MamlSyntax - { - public MamlSyntax() - { - // default for parameter set names is __AllParameterSets - //commented out for future consideration. - //ParameterSetName = "__AllParameterSets"; - } - - public string ParameterSetName { get; set; } - - public bool IsDefault { get; set; } - - public List Parameters { get { return _parameters; } } - - private List _parameters = new List(); - } -} diff --git a/v1/src/Markdown.MAML/Model/Markdown/CodeBlockNode.cs b/v1/src/Markdown.MAML/Model/Markdown/CodeBlockNode.cs deleted file mode 100644 index da554ece..00000000 --- a/v1/src/Markdown.MAML/Model/Markdown/CodeBlockNode.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace Markdown.MAML.Model.Markdown -{ - public class CodeBlockNode : TextNode - { - public string LanguageMoniker { get; private set; } - - public override MarkdownNodeType NodeType - { - get { return MarkdownNodeType.CodeBlock; } - } - - public CodeBlockNode(string languageMoniker, string codeBlockContents, SourceExtent sourceExtent) - : base(codeBlockContents.Trim(), sourceExtent) - { - if (!string.IsNullOrEmpty(languageMoniker)) - { - this.LanguageMoniker = languageMoniker; - } - } - } -} diff --git a/v1/src/Markdown.MAML/Model/Markdown/DocumentNode.cs b/v1/src/Markdown.MAML/Model/Markdown/DocumentNode.cs deleted file mode 100644 index 89a499c1..00000000 --- a/v1/src/Markdown.MAML/Model/Markdown/DocumentNode.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System.Collections.Generic; - -namespace Markdown.MAML.Model.Markdown -{ - public class DocumentNode : MarkdownNode - { - private List childNodes = new List(); - - public override MarkdownNodeType NodeType - { - get { return MarkdownNodeType.Document; } - } - - public IEnumerable Children { get; protected set; } - - public DocumentNode() - { - this.Children = this.childNodes; - } - - public void AddChildNode(MarkdownNode childNode) - { - this.childNodes.Add(childNode); - } - } -} diff --git a/v1/src/Markdown.MAML/Model/Markdown/HardBreakSpan.cs b/v1/src/Markdown.MAML/Model/Markdown/HardBreakSpan.cs deleted file mode 100644 index a711840c..00000000 --- a/v1/src/Markdown.MAML/Model/Markdown/HardBreakSpan.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Markdown.MAML.Model.Markdown -{ - public class HardBreakSpan : ParagraphSpan - { - public HardBreakSpan(SourceExtent sourceExtent) - : base("\n", sourceExtent, Parser.ParserMode.Full) - { - } - } -} diff --git a/v1/src/Markdown.MAML/Model/Markdown/HeadingNode.cs b/v1/src/Markdown.MAML/Model/Markdown/HeadingNode.cs deleted file mode 100644 index dc62af74..00000000 --- a/v1/src/Markdown.MAML/Model/Markdown/HeadingNode.cs +++ /dev/null @@ -1,24 +0,0 @@ -namespace Markdown.MAML.Model.Markdown -{ - public class HeadingNode : TextNode - { - public override MarkdownNodeType NodeType - { - get { return MarkdownNodeType.Heading; } - } - - public int HeadingLevel { get; private set; } - - /// - /// Additional options that determine how the section will be formated when rendering markdown. This options will be passed on to MAML models when they are generated. - /// - public SectionFormatOption FormatOption { get; private set; } - - public HeadingNode(string headingText, int headingLevel, SourceExtent sourceExtent, SectionFormatOption formatOption) - : base(headingText, sourceExtent) - { - this.HeadingLevel = headingLevel; - this.FormatOption = formatOption; - } - } -} diff --git a/v1/src/Markdown.MAML/Model/Markdown/HyperlinkSpan.cs b/v1/src/Markdown.MAML/Model/Markdown/HyperlinkSpan.cs deleted file mode 100644 index 72b8cf94..00000000 --- a/v1/src/Markdown.MAML/Model/Markdown/HyperlinkSpan.cs +++ /dev/null @@ -1,15 +0,0 @@ -using Markdown.MAML.Parser; - -namespace Markdown.MAML.Model.Markdown -{ - public class HyperlinkSpan : ParagraphSpan - { - public string Uri { get; private set; } - - public HyperlinkSpan(string spanText, string uriText, SourceExtent sourceExtent, ParserMode parserMode) - : base(spanText, sourceExtent, parserMode) - { - this.Uri = uriText; - } - } -} diff --git a/v1/src/Markdown.MAML/Model/Markdown/MarkdownNode.cs b/v1/src/Markdown.MAML/Model/Markdown/MarkdownNode.cs deleted file mode 100644 index f9a48498..00000000 --- a/v1/src/Markdown.MAML/Model/Markdown/MarkdownNode.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Markdown.MAML.Model.Markdown -{ - public abstract class MarkdownNode - { - public abstract MarkdownNodeType NodeType { get; } - } -} diff --git a/v1/src/Markdown.MAML/Model/Markdown/MarkdownNodeType.cs b/v1/src/Markdown.MAML/Model/Markdown/MarkdownNodeType.cs deleted file mode 100644 index 6c7d3214..00000000 --- a/v1/src/Markdown.MAML/Model/Markdown/MarkdownNodeType.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Markdown.MAML.Model.Markdown -{ - public enum MarkdownNodeType - { - Unknown = 0, - Document, - Paragraph, - Heading, - CodeBlock - } -} diff --git a/v1/src/Markdown.MAML/Model/Markdown/ParagraphNode.cs b/v1/src/Markdown.MAML/Model/Markdown/ParagraphNode.cs deleted file mode 100644 index 60070f55..00000000 --- a/v1/src/Markdown.MAML/Model/Markdown/ParagraphNode.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System.Collections.Generic; - -namespace Markdown.MAML.Model.Markdown -{ - public class ParagraphNode : MarkdownNode - { - public override MarkdownNodeType NodeType - { - get { return MarkdownNodeType.Paragraph; } - } - - public IEnumerable Spans - { - get; - private set; - } - - public ParagraphNode(IEnumerable childSpans) - { - this.Spans = childSpans; - } - } -} diff --git a/v1/src/Markdown.MAML/Model/Markdown/ParagraphSpan.cs b/v1/src/Markdown.MAML/Model/Markdown/ParagraphSpan.cs deleted file mode 100644 index 84f7c412..00000000 --- a/v1/src/Markdown.MAML/Model/Markdown/ParagraphSpan.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Markdown.MAML.Parser; - -namespace Markdown.MAML.Model.Markdown -{ - public abstract class ParagraphSpan - { - public string Text { get; private set; } - - public SourceExtent SourceExtent { get; private set; } - - public ParserMode ParserMode { get; private set; } - - public ParagraphSpan(string spanText, SourceExtent sourceExtent, ParserMode parserMode) - { - this.Text = spanText; - this.SourceExtent = sourceExtent; - this.ParserMode = parserMode; - } - } -} diff --git a/v1/src/Markdown.MAML/Model/Markdown/SectionBody.cs b/v1/src/Markdown.MAML/Model/Markdown/SectionBody.cs deleted file mode 100644 index 4ced89ef..00000000 --- a/v1/src/Markdown.MAML/Model/Markdown/SectionBody.cs +++ /dev/null @@ -1,33 +0,0 @@ -namespace Markdown.MAML.Model.Markdown -{ - /// - /// A section of text with formatting options. - /// - public sealed class SectionBody - { - public SectionBody(string text, SectionFormatOption formatOption) - { - Text = text; - FormatOption = formatOption; - } - - public SectionBody(string text) - : this(text, SectionFormatOption.None) - { } - - /// - /// The text of the section body. - /// - public string Text { get; private set; } - - /// - /// Additional options that determine how the section will be formated when rendering markdown. - /// - public SectionFormatOption FormatOption { get; private set; } - - public override string ToString() - { - return Text; - } - } -} diff --git a/v1/src/Markdown.MAML/Model/Markdown/SectionFormatOption.cs b/v1/src/Markdown.MAML/Model/Markdown/SectionFormatOption.cs deleted file mode 100644 index 7c53f396..00000000 --- a/v1/src/Markdown.MAML/Model/Markdown/SectionFormatOption.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; - -namespace Markdown.MAML.Model.Markdown -{ - /// - /// Define options that determine how sections will be formated when rendering markdown. - /// - [Flags()] - public enum SectionFormatOption : byte - { - None = 0, - - /// - /// A line break should be added after the section header. - /// - LineBreakAfterHeader = 1 - } -} diff --git a/v1/src/Markdown.MAML/Model/Markdown/SourceExtent.cs b/v1/src/Markdown.MAML/Model/Markdown/SourceExtent.cs deleted file mode 100644 index d12bf81b..00000000 --- a/v1/src/Markdown.MAML/Model/Markdown/SourceExtent.cs +++ /dev/null @@ -1,87 +0,0 @@ -using System.Diagnostics; - -namespace Markdown.MAML.Model.Markdown -{ - public class SourceRange - { - public int Start { get; private set; } - - public int End { get; private set; } - - public SourceRange(int start, int end) - { - this.Start = start; - this.End = end; - } - } - - [DebuggerDisplay("StartPos = (L: {Line.Start}, C: {Column.Start}), EndPos = (L: {Line.End}, C: {Column.End}), Text = {OriginalText}")] - public class SourceExtent - { - public string File { get; private set; } - - public SourceRange Line { get; private set; } - - public SourceRange Column { get; private set; } - - public SourceRange Offset { get; private set; } - - public string OriginalText { get; private set; } - - public SourceExtent( - string sourceText, - int startOffset, - int endOffset, - int currentLineNumber, - int currentColumnNumber, - string file) - { - int newLineNumber = currentLineNumber; - int newColumnNumber = currentColumnNumber; - this.CalculatePositionFromNewlines( - sourceText, - startOffset, - endOffset, - ref newLineNumber, - ref newColumnNumber); - - this.File = file; - this.Offset = new SourceRange(startOffset, endOffset); - this.Line = new SourceRange(currentLineNumber, newLineNumber); - this.Column = new SourceRange(currentColumnNumber, newColumnNumber); - this.OriginalText = - sourceText.Substring( - this.Offset.Start, - this.Offset.End - this.Offset.Start); - } - - private void CalculatePositionFromNewlines( - string subString, - int startOffset, - int endOffset, - ref int lineNumber, - ref int columnNumber) - { - // This method assumes that lineNumber and columnNumber just need to be - // updated because they are running counters for the current position. - - int offset; - int lineStartOffset = startOffset; - for (offset = startOffset; offset < endOffset; offset++) - { - if (subString[offset] == '\n') - { - lineNumber++; - - // Keep track of the offset number that starts this line so - // we can use it to calculate the new column position - lineStartOffset = offset + 1; - } - } - - // The new column position is the offset from the current line's - // starting offset - columnNumber += offset - lineStartOffset; - } - } -} diff --git a/v1/src/Markdown.MAML/Model/Markdown/TextNode.cs b/v1/src/Markdown.MAML/Model/Markdown/TextNode.cs deleted file mode 100644 index 23b2936d..00000000 --- a/v1/src/Markdown.MAML/Model/Markdown/TextNode.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace Markdown.MAML.Model.Markdown -{ - public abstract class TextNode : MarkdownNode - { - public string Text { get; private set; } - - public SourceExtent SourceExtent { get; private set; } - - public TextNode(string textContents, SourceExtent sourceExtent) - { - this.Text = textContents; - this.SourceExtent = sourceExtent; - } - } -} diff --git a/v1/src/Markdown.MAML/Model/Markdown/TextSpan.cs b/v1/src/Markdown.MAML/Model/Markdown/TextSpan.cs deleted file mode 100644 index 96df5d04..00000000 --- a/v1/src/Markdown.MAML/Model/Markdown/TextSpan.cs +++ /dev/null @@ -1,27 +0,0 @@ -using Markdown.MAML.Parser; - -namespace Markdown.MAML.Model.Markdown -{ - public enum TextSpanStyle - { - Normal, - Bold, - Italic - } - - public class TextSpan : ParagraphSpan - { - public TextSpanStyle Style { get; private set; } - - public TextSpan(string spanText, SourceExtent sourceExtent, ParserMode parserMode, TextSpanStyle spanStyle = TextSpanStyle.Normal) - : base( - parserMode == ParserMode.Full - ? MarkdownParser.UnwindMarkdownCharsEscaping(spanText.Trim()) - : spanText, - sourceExtent, - parserMode) - { - this.Style = spanStyle; - } - } -} diff --git a/v1/src/Markdown.MAML/Model/YAML/YamlCommand.cs b/v1/src/Markdown.MAML/Model/YAML/YamlCommand.cs deleted file mode 100644 index 8e77a634..00000000 --- a/v1/src/Markdown.MAML/Model/YAML/YamlCommand.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.Collections.Generic; - -namespace Markdown.MAML.Model.YAML -{ - public class YamlCommand - { - public List Examples { get; set; } - public List Inputs { get; set; } - public List Links { get; set; } - public YamlModule Module { get; set; } - public string Name { get; set; } - public string Notes { get; set; } - public List OptionalParameters { get; set; } - public List Outputs { get; set; } - public List RequiredParameters { get; set; } - public string Remarks { get; set; } - public string Summary { get; set; } - public List Syntaxes { get; set; } - } -} diff --git a/v1/src/Markdown.MAML/Model/YAML/YamlExample.cs b/v1/src/Markdown.MAML/Model/YAML/YamlExample.cs deleted file mode 100644 index 7a6ccfc1..00000000 --- a/v1/src/Markdown.MAML/Model/YAML/YamlExample.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Markdown.MAML.Model.YAML -{ - public class YamlExample - { - public string Name { get; set; } - public string PreCode { get; set; } - public string Code { get; set; } - public string PostCode { get; set; } - } -} \ No newline at end of file diff --git a/v1/src/Markdown.MAML/Model/YAML/YamlInputOutput.cs b/v1/src/Markdown.MAML/Model/YAML/YamlInputOutput.cs deleted file mode 100644 index 1c678ebd..00000000 --- a/v1/src/Markdown.MAML/Model/YAML/YamlInputOutput.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Markdown.MAML.Model.YAML -{ - public class YamlInputOutput - { - public string Type { get; set; } - public string Description { get; set; } - } -} \ No newline at end of file diff --git a/v1/src/Markdown.MAML/Model/YAML/YamlLink.cs b/v1/src/Markdown.MAML/Model/YAML/YamlLink.cs deleted file mode 100644 index 06976c75..00000000 --- a/v1/src/Markdown.MAML/Model/YAML/YamlLink.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Markdown.MAML.Model.YAML -{ - public class YamlLink - { - public string Href { get; set; } - public string Text { get; set; } - } -} \ No newline at end of file diff --git a/v1/src/Markdown.MAML/Model/YAML/YamlModule.cs b/v1/src/Markdown.MAML/Model/YAML/YamlModule.cs deleted file mode 100644 index 1a766d18..00000000 --- a/v1/src/Markdown.MAML/Model/YAML/YamlModule.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Markdown.MAML.Model.YAML -{ - public class YamlModule - { - public string Name { get; set; } - } -} \ No newline at end of file diff --git a/v1/src/Markdown.MAML/Model/YAML/YamlParameter.cs b/v1/src/Markdown.MAML/Model/YAML/YamlParameter.cs deleted file mode 100644 index 164dc83a..00000000 --- a/v1/src/Markdown.MAML/Model/YAML/YamlParameter.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.Collections.Generic; - -namespace Markdown.MAML.Model.YAML -{ - public class YamlParameter - { - public string Name { get; set; } - public bool AcceptWildcardCharacters { get; set; } - public List Aliases { get; set; } - public string DefaultValue { get; set; } - public string Description { get; set; } - public List ParameterValueGroup { get; set; } - public string PipelineInput { get; set; } - public string Position { get; set; } - public string Type { get; set; } - } -} \ No newline at end of file diff --git a/v1/src/Markdown.MAML/Model/YAML/YamlSyntax.cs b/v1/src/Markdown.MAML/Model/YAML/YamlSyntax.cs deleted file mode 100644 index bf7e3c69..00000000 --- a/v1/src/Markdown.MAML/Model/YAML/YamlSyntax.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.Collections.Generic; - -namespace Markdown.MAML.Model.YAML -{ - public class YamlSyntax - { - public string ParameterValueGroup { get; set; } - public bool IsDefault { get; set; } - public List Parameters { get; set; } - } -} \ No newline at end of file diff --git a/v1/src/Markdown.MAML/Parser/MarkdownParser.cs b/v1/src/Markdown.MAML/Parser/MarkdownParser.cs deleted file mode 100644 index 296d4c50..00000000 --- a/v1/src/Markdown.MAML/Parser/MarkdownParser.cs +++ /dev/null @@ -1,646 +0,0 @@ -using Markdown.MAML.Model; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text.RegularExpressions; -using Markdown.MAML.Model.Markdown; - -namespace Markdown.MAML.Parser -{ - public enum ParserMode - { - Full, - /// - /// It's aimed to be used in a merge scenario. - /// It will allow us preserve formatting existin Markdown as is. - /// It doesn't try to do the following: - /// - /// - escaping characters - /// - parse hyper-links - /// - handle soft-breaks and hard-breaks - /// - FormattingPreserve - } - - public class MarkdownParser - { - #region Private Fields - - DocumentNode _currentDocument; - private string _documentText; - MarkdownPatternList _markdownPatterns; - ParserMode _parserMode; - List _currentParagraphSpans; - Action _progressCallback; - Action _infoCallback; - int _reportByteCount; - - private static readonly string[] LINE_BREAKS = new[] { "\r\n", "\n" }; - private static readonly char[] YAML_SEPARATORS = new[] { ':' }; - - #endregion - - #region Public Methods - - public MarkdownParser() : this(null) {} - - public MarkdownParser(Action progressCallback, Action infoCallback) : this(progressCallback) - { - _infoCallback = infoCallback; - } - - public MarkdownParser(Action progressCallback) : this(progressCallback, 3000) { } - - /// - /// - /// Progress callback called sometimes and report that param1 of param2 bytes processed. - /// Call progressCallback every reportByteCount bytes. - public MarkdownParser(Action progressCallback, int reportByteCount) - { - _progressCallback = progressCallback; - _reportByteCount = reportByteCount; - } - - public DocumentNode ParseString(string[] markdownStrings) - { - // default is full - return ParseString(markdownStrings, ParserMode.Full, null); - } - - public DocumentNode ParseString(string[] markdownStrings, ParserMode parseMode, string path) - { - this._parserMode = parseMode; - this._path = path; - this.InitializePatternList(); - _currentDocument = new DocumentNode(); - - for (int i = 0; i < markdownStrings.Length; i++) - { - string markdownString = markdownStrings[i]; - // if there are more then 1 markdownString, we should report progress - // per strings, not for the whole string. - if (markdownStrings.Length > 1 && this._progressCallback != null) - { - this._progressCallback(i, markdownStrings.Length); - } - - if (string.IsNullOrWhiteSpace(markdownString)) - { - continue; - } - - // Trim the leading whitespace off of the string - // Skip YamlMetadata block at the begining, if present - _documentText = this.SkipYamlMetadataBlock(PrepareDocumentString(markdownString)); - - this.ParseDocument(markdownStrings.Length == 1); - } - - return _currentDocument; - } - - #endregion - - #region Initialization - - private void InitializePatternList() - { - _markdownPatterns = - new MarkdownPatternList - { - // Headers - { "hash_header", - @"(\#+)[ ]*(.+?)[ ]*\#*(\r\n)+", - this.CreateHashHeader }, - - // This is a dirty hack to tell avoid hash_headers, if it's not a beginning of a line - { "hash_header2", - @"(\r\n)+(\#+)[ ]*(.+?)[ ]*\#*(\r\n)+", - this.CreateHashHeader2 }, - - { "underline_header", - @"(.+?)[ ]*\r\n(==+|--+)[ ]*(\r\n)+", - this.CreateUnderlineHeader }, - - // Code blocks - { "tick_codeblock", - @"```(\w*)(\r\n)*((.|\r\n)*?)```(\r\n)*", - this.CreateTickCodeBlock } - }; - - if (this._parserMode == ParserMode.Full) - { - _markdownPatterns.Append( - new MarkdownPatternList - { - // Paragraph spans - { "hardbreak", - @"[ ]{2}\r\n", - this.CreateHardBreakSpan }, - - { "softbreak", - @"(\r\n){{1}}", - this.CreateSoftBreakSpan }, - - { "new_paragraph", - @"(\r\n){{2,}}", - this.CreateParagraph }, - - { "hyperlink", - @"\[(.+?)\]\((.*)\)", - this.CreateHyperlinkSpan }, - - { "bold", - @"\*\*(.+?)\*\*", - this.CreateBoldSpan }, - - { "italic", - @"\*(.+?)\*", - this.CreateItalicSpan }, - - { "bold2", - @"(? regexMatch.Index) - { - firstMatch = regexMatch; - firstMatchedPattern = markdownPattern; - if (regexMatch.Index == startOffset) - { - // no reason to continue - break; - } - } - } - } - - if (firstMatch != null) - { - // Gather all text before this point into a paragraph - if (firstMatch.Index > 0) - { - this.StartParagraph(); - - // Get the extent of the span text - SourceExtent spanExtent = - new SourceExtent( - _documentText, - startOffset, - firstMatch.Index, - currentLineNumber, - currentColumnNumber, - _path); - - this.CreateNormalSpan( - spanExtent.OriginalText, - spanExtent); - - // Make sure the line and column number are updated - // before calculating the position of the match - currentLineNumber = spanExtent.Line.End; - currentColumnNumber = spanExtent.Column.End; - } - - // Count the newlines in the entire span - SourceExtent matchExtent = - new SourceExtent( - _documentText, - firstMatch.Index, - firstMatch.Index + firstMatch.Length, - currentLineNumber, - currentColumnNumber, - _path); - - // Run the match action for the pattern - firstMatchedPattern.MatchAction(firstMatch, matchExtent); - - // Calculate the next offset, line, and column - startOffset = firstMatch.Index + firstMatch.Length; - currentLineNumber = matchExtent.Line.End; - currentColumnNumber = matchExtent.Column.End; - } - else - { - // Get the extent containing the remaining text - SourceExtent spanExtent = - new SourceExtent( - _documentText, - startOffset, - _documentText.Length, - currentLineNumber, - currentColumnNumber, - _path); - - // If no match found, treat the rest of the text as a span - this.CreateNormalSpan( - spanExtent.OriginalText, - spanExtent); - - startOffset = _documentText.Length; - } - } - - // Finish any remaining paragraph - this.FinishParagraph(); - } - - private void CreateHashHeader(Match regexMatch, SourceExtent sourceExtent) - { - this.FinishParagraph(); - - _currentDocument.AddChildNode( - new HeadingNode( - regexMatch.Groups[2].Value, - regexMatch.Groups[1].Value.Length, - sourceExtent, - - // Detect if a line break after the header exists. Mutiple line breaks will be reduced to one. - (regexMatch.Groups[3].Captures.Count > 1) ? SectionFormatOption.LineBreakAfterHeader : SectionFormatOption.None)); - } - - private void CreateHashHeader2(Match regexMatch, SourceExtent sourceExtent) - { - this.FinishParagraph(); - - _currentDocument.AddChildNode( - new HeadingNode( - regexMatch.Groups[3].Value, - regexMatch.Groups[2].Value.Length, - sourceExtent, - - // Detect if a line break after the header exists. Mutiple line breaks will be reduced to one. - (regexMatch.Groups[4].Captures.Count > 1) ? SectionFormatOption.LineBreakAfterHeader : SectionFormatOption.None)); - } - - private void CreateUnderlineHeader(Match regexMatch, SourceExtent sourceExtent) - { - this.FinishParagraph(); - - int headerLevel = - regexMatch.Groups[2].Value[0] == '=' ? - 1 : 2; - - _currentDocument.AddChildNode( - new HeadingNode( - regexMatch.Groups[1].Value, - headerLevel, - sourceExtent, - - // Detect if a line break after the header exists. Mutiple line breaks will be reduced to one. - (regexMatch.Groups[3].Captures.Count > 1) ? SectionFormatOption.LineBreakAfterHeader : SectionFormatOption.None)); - } - - private void CreateTickCodeBlock(Match regexMatch, SourceExtent sourceExtent) - { - this.FinishParagraph(); - - _currentDocument.AddChildNode( - new CodeBlockNode( - regexMatch.Groups[1].Value, - regexMatch.Groups[3].Value, - sourceExtent)); - } - - private void CreateNormalSpan(string spanText, SourceExtent sourceExtent) - { - this.StartParagraph(); - - // TODO: Replace all newlines with spaces? We - // might want to add line breaks only when the - // user has intentionally typed a hard break string - // ( \r\n) - - // If the span is merely whitespace, don't add it - if (!string.IsNullOrWhiteSpace(spanText)) - { - _currentParagraphSpans.Add( - new TextSpan( - spanText, - sourceExtent, - this._parserMode)); - } - } - - private void CreateItalicSpan(Match regexMatch, SourceExtent sourceExtent) - { - this.StartParagraph(); - - _currentParagraphSpans.Add( - new TextSpan( - regexMatch.Groups[1].Value, - sourceExtent, - this._parserMode, - TextSpanStyle.Italic)); - } - - private void CreateBoldSpan(Match regexMatch, SourceExtent sourceExtent) - { - this.StartParagraph(); - - _currentParagraphSpans.Add( - new TextSpan( - regexMatch.Groups[1].Value, - sourceExtent, - this._parserMode, - TextSpanStyle.Bold)); - } - - private void CreateHyperlinkSpan(Match regexMatch, SourceExtent sourceExtent) - { - this.StartParagraph(); - - _currentParagraphSpans.Add( - new HyperlinkSpan( - regexMatch.Groups[1].Value, - regexMatch.Groups[2].Value, - sourceExtent, - this._parserMode)); - } - - private void CreateSoftBreakSpan(Match regexMatch, SourceExtent sourceExtent) - { - // Don't create a span? - } - - private void CreateHardBreakSpan(Match regexMatch, SourceExtent sourceExtent) - { - this.StartParagraph(); - - _currentParagraphSpans.Add( - new HardBreakSpan( - sourceExtent)); - } - - private void CreateParagraph(Match regexMatch, SourceExtent sourceExtent) - { - this.FinishParagraph(); - this.StartParagraph(); - } - - #endregion - - #region Parser State Management - - private void StartParagraph() - { - if (_currentParagraphSpans == null) - { - _currentParagraphSpans = new List(); - } - } - - private void FinishParagraph() - { - if (_currentParagraphSpans != null && - _currentParagraphSpans.Count > 0) - { - _currentDocument.AddChildNode( - new ParagraphNode( - _currentParagraphSpans)); - - _currentParagraphSpans = null; - } - } - - #endregion - - #region Helper Methods - - /// - /// we only parse simple key-value pairs here - /// - /// - /// - internal static Dictionary ParseYamlKeyValuePairs(string yamlSnippet) - { - var result = new Dictionary(StringComparer.OrdinalIgnoreCase); - foreach (string lineIterator in yamlSnippet.Split(LINE_BREAKS, StringSplitOptions.None)) - { - var line = lineIterator.Trim(); - if (string.IsNullOrEmpty(line.Trim())) - { - continue; - } - - string[] parts = line.Split(YAML_SEPARATORS, 2); - if (parts.Length != 2) - { - throw new ArgumentException("Invalid yaml: expected simple key-value pairs"); - } - - var key = parts[0].Trim(); - var value = parts[1].Trim(); - // we treat empty value as null - result[key] = string.IsNullOrEmpty(value) ? null : value; - } - - return result; - } - - public static Dictionary GetYamlMetadata(string markdownString) - { - markdownString = PrepareDocumentString(markdownString); - int endPosition = GetYamlMetadataBlockEndOffset(markdownString); - if (endPosition < 0) - { - return null; - } - else - { - const int OFFSET = 5; - return ParseYamlKeyValuePairs(markdownString.Substring(OFFSET, endPosition - OFFSET)); - } - } - - private static int GetYamlMetadataBlockEndOffset(string markdownString) - { - const int OFFSET = 5; - if (markdownString.StartsWith("---\r\n")) - { - return markdownString.IndexOf("\r\n---", OFFSET); - } - - return -1; - } - - private string SkipYamlMetadataBlock(string documentString) - { - int offset = GetYamlMetadataBlockEndOffset(documentString); - if (offset >= 0) - { - const int OFFSET = 5; - return documentString.Substring(offset + OFFSET).TrimStart(); - } - - return documentString; - } - - private static string PrepareDocumentString(string documentString) - { - // Trim any leading whitespace off of the string - documentString = documentString.TrimStart(); - - // Replace any invalid characters - // TODO: Find a better way to deal with this problem in a general way - documentString = documentString.Replace('–', '-'); - - // Make sure all newlines are \r\n. In some environments, - // verbatim string literals have \r instead of \r\n. - // regex source: http://stackoverflow.com/questions/3219014/what-is-a-cross-platform-regex-for-removal-of-line-breaks - return Regex.Replace(documentString, "\r\n?|\n", "\r\n"); - } - - public static string UnwindMarkdownCharsEscaping(string spanText) - { - // this is reverse for the code in MarkdownV2Renderer.GetEscapedMarkdownText() - spanText = spanText - .Replace("\r\n([^\r])", "$1") - - .Replace(@"\[", @"[") - .Replace(@"\]", @"]") - // per https://github.com/PowerShell/platyPS/issues/121 we don't perform escaping for () in markdown renderer, but we do in the parser - .Replace(@"\(", @"(") - .Replace(@"\)", @")") - - .Replace(@"\`", @"`") - - .Replace(@"\<", "<") - .Replace(@"\>", ">") - - .Replace(@"\_", "_") - .Replace(@"\*", "*") - - .Replace(@"\\", @"\"); - - // any dummy value with length >= 2 - _PrevString = "foo"; - _InList = false; - - return Regex.Replace(spanText, "([^\r\n]*)(\r\n|$)", new MatchEvaluator(LineBreaksMatchEvaluater)).Replace(" \r\n", "\r\n").Trim(); - } - - // hacky state for matcher, it would cause race condition if we decided to run in parallel - private static string _PrevString; - private static bool _InList; - private string _path; - - internal static bool HasListPrefix(string s) - { - if (s.Length >= 2) - { - if (s[0] == '-' && s[1] == '-' || - s[0] == '-' && s[1] == ' ' || - s[0] == '*' && s[1] == ' ') - { - return true; - } - } - - return false; - } - - private static string LineBreaksMatchEvaluater(Match match) - { - // here we want proper line breaks - // if it's a list, then preserve line-breaks. - // otherwise, convert one line-break into a space and two-line breaks into a line-break. - - var g1 = _PrevString; - var g2 = match.Groups[1].Value; - _PrevString = g2; - - if (string.IsNullOrWhiteSpace(g2)) - { - return "\r\n"; - } - - if (HasListPrefix(g1) && HasListPrefix(g2)) - { - // this is a list - _InList = true; - return "\r\n" + g2; - } - - if (_InList) - { - // now we are not in list, so we just finished it - // we preserve one more line ending - _InList = false; - g2 = "\r\n" + g2; - } - - return g2 + " "; - } - - /// - /// Callback to PowerShell host session to display reporting info on the console. - /// - /// - /// - private void Report(string format, params object[] objects) - { - if (_infoCallback != null) - { - _infoCallback.Invoke(string.Format(format, objects)); - } - } - - #endregion - } -} diff --git a/v1/src/Markdown.MAML/Parser/MarkdownPattern.cs b/v1/src/Markdown.MAML/Parser/MarkdownPattern.cs deleted file mode 100644 index d5440623..00000000 --- a/v1/src/Markdown.MAML/Parser/MarkdownPattern.cs +++ /dev/null @@ -1,43 +0,0 @@ -using Markdown.MAML.Model.Markdown; -using System; -using System.Text.RegularExpressions; - -namespace Markdown.MAML.Parser -{ - public class MarkdownPattern - { - private Regex patternRegex; - - public string PatternName { get; private set;} - - public string PatternString { get; private set; } - - public Action MatchAction { get; private set; } - - public MarkdownPattern( - string patternName, - string patternString, - Action matchAction) - { - this.PatternName = patternName; - this.PatternString = patternString; - this.MatchAction = matchAction; - - this.patternRegex = - new Regex( - patternString, - RegexOptions.IgnorePatternWhitespace | - RegexOptions.Compiled); - } - - public bool TryMatchString(string inputString, int startOffset, out Match regexMatch) - { - // the intention is to speed-up match process for the long strings. - // This number is completely orbitrary - // TODO: remove this perf hack - const int longestExpectedParagraphSpan = 10000; - regexMatch = this.patternRegex.Match(inputString, startOffset, Math.Min(inputString.Length - startOffset, longestExpectedParagraphSpan)); - return regexMatch.Success; - } - } -} diff --git a/v1/src/Markdown.MAML/Parser/MarkdownPatternList.cs b/v1/src/Markdown.MAML/Parser/MarkdownPatternList.cs deleted file mode 100644 index 3945e4c6..00000000 --- a/v1/src/Markdown.MAML/Parser/MarkdownPatternList.cs +++ /dev/null @@ -1,47 +0,0 @@ -using Markdown.MAML.Model.Markdown; -using System; -using System.Collections.Generic; -using System.Text.RegularExpressions; - -namespace Markdown.MAML.Parser -{ - /// - /// This class provides a way to concisely define a list of - /// MarkdownPatterns using C# initializer syntax. The Add - /// method here is what gets invoked when using the following - /// initializer syntax: - /// - /// new MarkdownPatternList - /// { - /// { "patternName", "regexPatternString", SomeFunctionName } - /// } - /// - public class MarkdownPatternList : IEnumerable - { - private List _patternList = new List(); - - public void Add(string patternName, string regexPattern, Action matchAction) - { - _patternList.Add( - new MarkdownPattern( - patternName, - regexPattern, - matchAction)); - } - - public void Append(MarkdownPatternList list) - { - _patternList.AddRange(list); - } - - public IEnumerator GetEnumerator() - { - return _patternList.GetEnumerator(); - } - - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() - { - return _patternList.GetEnumerator(); - } - } -} diff --git a/v1/src/Markdown.MAML/Properties/AssemblyInfo.cs b/v1/src/Markdown.MAML/Properties/AssemblyInfo.cs deleted file mode 100644 index 652f567a..00000000 --- a/v1/src/Markdown.MAML/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,3 +0,0 @@ -using System.Runtime.CompilerServices; - -[assembly: InternalsVisibleToAttribute("Markdown.MAML.Test")] diff --git a/v1/src/Markdown.MAML/Renderer/MamlRenderer.cs b/v1/src/Markdown.MAML/Renderer/MamlRenderer.cs deleted file mode 100644 index ed041bd8..00000000 --- a/v1/src/Markdown.MAML/Renderer/MamlRenderer.cs +++ /dev/null @@ -1,234 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using Markdown.MAML.Model.MAML; -using System.Xml.Linq; - -namespace Markdown.MAML.Renderer -{ - /// - /// This class contain logic to render maml from the Model. - /// - public class MamlRenderer - { - private static XNamespace mshNS = XNamespace.Get("http://msh"); - private static XNamespace mamlNS = XNamespace.Get("http://schemas.microsoft.com/maml/2004/10"); - private static XNamespace commandNS = XNamespace.Get("http://schemas.microsoft.com/maml/dev/command/2004/10"); - private static XNamespace devNS = XNamespace.Get("http://schemas.microsoft.com/maml/dev/2004/10"); - private static XNamespace msHelpNS = XNamespace.Get("http://msdn.microsoft.com/mshelp"); - - private static char examplePadChar = '-'; - private static char space = ' '; - - /// - /// - /// - /// - /// Don't include header and footer for xml doc - /// - public string MamlModelToString(IEnumerable mamlCommands) - { - var document = new XDocument( - new XDeclaration("1.0", "utf-8", null), - new XElement(mshNS + "helpItems", - new XAttribute("schema","maml"), - - mamlCommands.Select(CreateCommandElement))); - - var memoryStream = new MemoryStream(); - using (var writer = new StreamWriter(memoryStream, Encoding.UTF8)) - { - document.Save(writer, SaveOptions.OmitDuplicateNamespaces); - writer.Flush(); - - memoryStream.Seek(0, SeekOrigin.Begin); - using (var reader = new StreamReader(memoryStream, Encoding.UTF8)) - { - return RenderCleaner.NormalizeWhitespaces(reader.ReadToEnd()); - } - } - } - - private static XElement CreateCommandElement(MamlCommand command) - { - var commandParts = command.Name.Split('-'); - var verb = commandParts[0]; - var noun = command.Name.Substring(Math.Min(verb.Length + 1, command.Name.Length)); - - return new XElement(commandNS + "command", - new XAttribute(XNamespace.Xmlns + "maml", mamlNS), - new XAttribute(XNamespace.Xmlns + "command", commandNS), - new XAttribute(XNamespace.Xmlns + "dev", devNS), - new XAttribute(XNamespace.Xmlns + "MSHelp", msHelpNS), - - new XElement(commandNS + "details", - new XElement(commandNS + "name", command.Name), - new XElement(commandNS + "verb", verb), - new XElement(commandNS + "noun", noun), - new XElement(mamlNS + "description", GenerateParagraphs(command.Synopsis?.Text))), - new XElement(mamlNS + "description", GenerateParagraphs(command.Description?.Text)), - new XElement(commandNS + "syntax", command.Syntax.Select(syn => CreateSyntaxItem(syn, command))), - new XElement(commandNS + "parameters", command.Parameters.Select(param => CreateParameter(param))), - new XElement(commandNS + "inputTypes", command.Inputs.Select(input => CreateInput(input))), - new XElement(commandNS + "returnValues", command.Outputs.Select(output => CreateOutput(output))), - new XElement(mamlNS + "alertSet", - new XElement(mamlNS + "alert", GenerateParagraphs(command.Notes?.Text))), - new XElement(commandNS + "examples", command.Examples.Select(example => CreateExample(example))), - new XElement(commandNS + "relatedLinks", command.Links.Select(link => CreateLink(link)))); - } - - private static IEnumerable GenerateParagraphs(string text) - { - if (text != null) - { - return text.Split(new string[] { "\r\n" }, StringSplitOptions.None) - .Select(para => new XElement(mamlNS + "para", para)); - } - - return Enumerable.Empty(); - } - - private static XElement CreateSyntaxItem(MamlSyntax syntaxItem, MamlCommand command) - { - return new XElement(commandNS + "syntaxItem", - new XElement(mamlNS + "name", command.Name), - syntaxItem.Parameters.Select(param => CreateParameter(param, isSyntax: true))); - } - - - /// - /// Creates a command:parameter element - /// - /// The parsed parameter object - /// Render using the format for syntax blocks where we do not render [switch] - /// - private static XElement CreateParameter(MamlParameter param, bool isSyntax = false) - { - string mamlType = ConvertPSTypeToMamlType(param); - bool isSwitchParameter = mamlType == "SwitchParameter" || mamlType == "System.Management.Automation.SwitchParameter"; - - return new XElement(commandNS + "parameter", - new XAttribute("required", param.Required), - new XAttribute("variableLength", param.VariableLength), - new XAttribute("globbing", param.Globbing), - new XAttribute("pipelineInput", param.PipelineInput), - new XAttribute("position", param.Position.ToLower()), - new XAttribute("aliases", param.Aliases.Any() ? string.Join(", ", param.Aliases) : "none"), - - new XElement(mamlNS + "name", param.Name), - new XElement(mamlNS + "description", GenerateParagraphs(param.Description)), - isSyntax && param.ParameterValueGroup.Any() - ? new XElement(commandNS + "parameterValueGroup", param.ParameterValueGroup.Select(pvg => CreateParameterValueGroup(pvg))) - : null, - // we don't add [switch] info to make it appear good - !isSyntax || !isSwitchParameter - ? new XElement(commandNS + "parameterValue", - new XAttribute("required", param.ValueRequired), - new XAttribute("variableLength", param.ValueVariableLength), - mamlType) - : null, - new XElement(devNS + "type", - new XElement(mamlNS + "name", mamlType), - new XElement(mamlNS + "uri")), - new XElement(devNS + "defaultValue", - isSwitchParameter && (string.IsNullOrEmpty(param.DefaultValue) || param.DefaultValue == "None") - ? "False" - : param.DefaultValue ?? "None")); - } - - private static XElement CreateParameterValueGroup(string pvg) - { - return new XElement(commandNS + "parameterValue", - new XAttribute("required", "false"), new XAttribute(commandNS + "variableLength", "false"), - pvg); - } - - private static XElement CreateInput(MamlInputOutput input) - { - return new XElement(commandNS + "inputType", - new XElement(devNS + "type", - new XElement(mamlNS + "name", input.TypeName)), - new XElement(mamlNS + "description", GenerateParagraphs(input.Description))); - } - - private static XElement CreateOutput(MamlInputOutput output) - { - return new XElement(commandNS + "returnValue", - new XElement(devNS + "type", - new XElement(mamlNS + "name", output.TypeName)), - new XElement(mamlNS + "description", GenerateParagraphs(output.Description))); - } - - private static XElement CreateExample(MamlExample example) - { - return new XElement(commandNS + "example", - new XElement(mamlNS + "title", PadExampleTitle(example.Title)), - new XElement(devNS + "code", string.Join("\r\n\r\n", example.Code.Select(block => block.Text))), - new XElement(devNS + "remarks", GenerateParagraphs(example.Remarks))); - } - - private static XElement CreateLink(MamlLink link) - { - // PowerShell help engine is not happy, when LinkUri doesn't represent a valid URI - // but it's often convinient to have it (i.e. relative links between markdown files on github). - // so, we are ignoring non-uri links when rendering the final maml. - // https://github.com/PowerShell/platyPS/issues/164 - if (link.IsSimplifiedTextLink) - { - return null; - } - - string uriValue = string.Empty; - Uri uri; - if(Uri.TryCreate(link.LinkUri, UriKind.Absolute, out uri)) - { - uriValue = link.LinkUri; - } - - return new XElement(mamlNS + "navigationLink", - new XElement(mamlNS + "linkText", link.LinkName), - new XElement(mamlNS + "uri", uriValue)); - } - - /// - /// Generate (-) padding for example title - /// - /// The title to pa. - /// The title padded by dashes - private static string PadExampleTitle(string title) - { - // Filter out edge cases where title is too long or empty - if (string.IsNullOrWhiteSpace(title) || title.Length >= 62) - { - return title; - } - - // Pad example title with dash (-) to increase readability up to 64 characters - - int padLength = (64 - title.Length - 2) / 2; - - return title - .PadLeft(title.Length + 1, space) - .PadRight(title.Length + 2, space) - .PadLeft(title.Length + 2 + padLength, examplePadChar) - .PadRight(title.Length + 2 + 2 * padLength, examplePadChar); - } - - private static string ConvertPSTypeToMamlType(MamlParameter parameter) - { - if (parameter.Type == null) - { - return string.Empty; - } - - if (parameter.IsSwitchParameter()) - { - return "SwitchParameter"; - } - - return parameter.Type; - } - } -} diff --git a/v1/src/Markdown.MAML/Renderer/Markdownv2Renderer.cs b/v1/src/Markdown.MAML/Renderer/Markdownv2Renderer.cs deleted file mode 100644 index 32c7ddb9..00000000 --- a/v1/src/Markdown.MAML/Renderer/Markdownv2Renderer.cs +++ /dev/null @@ -1,607 +0,0 @@ -using Markdown.MAML.Model.MAML; -using Markdown.MAML.Parser; -using Markdown.MAML.Resources; -using Markdown.MAML.Transformer; -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading.Tasks; -using Markdown.MAML.Model.Markdown; - -namespace Markdown.MAML.Renderer -{ - /// - /// Renders MamlModel as markdown with schema v 2.0.0 - /// - public class MarkdownV2Renderer - { - private StringBuilder _stringBuilder = new StringBuilder(); - - private ParserMode _mode; - - public int MaxSyntaxWidth { get; private set; } - - private const string NewLine = "\r\n"; - - /// - /// 110 is a good width value, because it doesn't cause github to add horizontal scroll bar - /// - public const int DEFAULT_SYNTAX_WIDTH = 110; - - public MarkdownV2Renderer(ParserMode mode) : this(mode, DEFAULT_SYNTAX_WIDTH) { } - - public MarkdownV2Renderer(ParserMode mode, int maxSyntaxWidth) - { - this.MaxSyntaxWidth = maxSyntaxWidth; - this._mode = mode; - } - - public string MamlModelToString(MamlCommand mamlCommand, bool skipYamlHeader) - { - return MamlModelToString(mamlCommand, null, skipYamlHeader); - } - - public string MamlModelToString(MamlCommand mamlCommand, Hashtable yamlHeader) - { - return MamlModelToString(mamlCommand, yamlHeader, false); - } - - private string MamlModelToString(MamlCommand mamlCommand, Hashtable yamlHeader, bool skipYamlHeader) - { - // clear, so we can re-use this instance - _stringBuilder.Clear(); - if (!skipYamlHeader) - { - if (yamlHeader == null) - { - yamlHeader = new Hashtable(); - } - - // put version there - yamlHeader["schema"] = "2.0.0"; - AddYamlHeader(yamlHeader); - } - - AddCommand(mamlCommand); - - // at the end, just normalize all ends - return RenderCleaner.NormalizeLineBreaks( - RenderCleaner.NormalizeWhitespaces( - RenderCleaner.NormalizeQuotesAndDashes( - _stringBuilder.ToString()))); - } - - private void AddYamlHeader(Hashtable yamlHeader) - { - _stringBuilder.AppendFormat("---{0}", NewLine); - - // Use a sorted dictionary to force the metadata into alphabetical order by key for consistency. - var sortedHeader = new SortedDictionary(StringComparer.OrdinalIgnoreCase); - foreach (DictionaryEntry pair in yamlHeader) - { - sortedHeader[pair.Key.ToString()] = pair.Value == null ? "" : pair.Value.ToString(); - } - - foreach (var pair in sortedHeader) - { - AppendYamlKeyValue(pair.Key, pair.Value); - } - - _stringBuilder.AppendFormat("---{0}{0}", NewLine); - } - - private void AddCommand(MamlCommand command) - { - AddHeader(ModelTransformerBase.COMMAND_NAME_HEADING_LEVEL, command.Name); - AddEntryHeaderWithText(MarkdownStrings.SYNOPSIS, command.Synopsis); - AddSyntax(command); - AddEntryHeaderWithText(MarkdownStrings.DESCRIPTION, command.Description); - AddExamples(command); - AddParameters(command); - AddInputs(command); - AddOutputs(command); - AddEntryHeaderWithText(MarkdownStrings.NOTES, command.Notes); - AddLinks(command); - } - - private void AddLinks(MamlCommand command) - { - var extraNewLine = command.Links != null && command.Links.Count > 0; - - AddHeader(ModelTransformerBase.COMMAND_ENTRIES_HEADING_LEVEL, MarkdownStrings.RELATED_LINKS, extraNewLine); - foreach (var link in command.Links) - { - if (link.IsSimplifiedTextLink) - { - _stringBuilder.AppendFormat("{0}", link.LinkName); - } - else - { - var name = link.LinkName; - if (string.IsNullOrEmpty(name)) - { - // we need a valid name to produce a valid markdown - name = link.LinkUri; - } - - _stringBuilder.AppendFormat("[{0}]({1}){2}{2}", name, link.LinkUri, NewLine); - } - } - } - - private void AddInputOutput(MamlInputOutput io) - { - if (string.IsNullOrEmpty(io.TypeName) && string.IsNullOrEmpty(io.Description)) - { - // in this case ignore - return; - } - - var extraNewLine = ShouldBreak(io.FormatOption); - AddHeader(ModelTransformerBase.INPUT_OUTPUT_TYPENAME_HEADING_LEVEL, io.TypeName, extraNewLine); - AddParagraphs(io.Description); - } - - private void AddOutputs(MamlCommand command) - { - AddHeader(ModelTransformerBase.COMMAND_ENTRIES_HEADING_LEVEL, MarkdownStrings.OUTPUTS); - foreach (var io in command.Outputs) - { - AddInputOutput(io); - } - } - - private void AddInputs(MamlCommand command) - { - AddHeader(ModelTransformerBase.COMMAND_ENTRIES_HEADING_LEVEL, MarkdownStrings.INPUTS); - foreach (var io in command.Inputs) - { - AddInputOutput(io); - } - } - - private void AddParameters(MamlCommand command) - { - AddHeader(ModelTransformerBase.COMMAND_ENTRIES_HEADING_LEVEL, MarkdownStrings.PARAMETERS); - foreach (var param in command.Parameters) - { - AddParameter(param, command); - } - - if (command.IsWorkflow) - { - AddWorkflowParameters(); - } - - // Workflows always support CommonParameters - if (command.SupportCommonParameters || command.IsWorkflow) - { - AddCommonParameters(); - } - } - - private void AddCommonParameters() - { - AddHeader(ModelTransformerBase.PARAMETERSET_NAME_HEADING_LEVEL, MarkdownStrings.CommonParametersToken, extraNewLine: false); - AddParagraphs(MarkdownStrings.CommonParametersText, noNewLines: false, skipAutoWrap: true); - } - - private void AddWorkflowParameters() - { - AddHeader(ModelTransformerBase.PARAMETERSET_NAME_HEADING_LEVEL, MarkdownStrings.WorkflowParametersToken, extraNewLine: false); - AddParagraphs(MarkdownStrings.WorkflowParametersText, noNewLines: false, skipAutoWrap: true); - } - - private Dictionary GetParamSetDictionary(string parameterName, List syntaxes) - { - var result = new Dictionary(); - foreach (var syntax in syntaxes) - { - foreach (var param in syntax.Parameters) - { - if (StringComparer.OrdinalIgnoreCase.Equals(parameterName, param.Name)) - { - if (string.IsNullOrEmpty(syntax.ParameterSetName)) - { - // Note (vors) : I guess that means it's applicable to all parameter sets, - // but it's hard to tell anymore... - result[ModelTransformerVersion2.ALL_PARAM_SETS_MONIKER] = param; - } - else - { - result[syntax.ParameterSetName] = param; - } - // there could be only one parameter in the param set with the same name - break; - } - } - } - return result; - } - - private List, MamlParameter>> SimplifyParamSets(Dictionary parameterMap) - { - var res = new List, MamlParameter>>(); - // using a O(n^2) algorithm, because it's simpler and n is very small. - foreach (var pair in parameterMap) - { - var seekValue = pair.Value; - var paramSetName = pair.Key; - bool found = false; - foreach (var tuple in res) - { - if (tuple.Item2.IsMetadataEqual(seekValue)) - { - tuple.Item1.Add(paramSetName); - found = true; - break; - } - } - - if (!found) - { - // create a new entry - var paramSets = new List(); - paramSets.Add(paramSetName); - res.Add(new Tuple, MamlParameter>(paramSets, seekValue)); - } - } - - return res; - } - - private string JoinWithComma(IEnumerable args) - { - if (args == null) - { - return ""; - } - - return string.Join(", ", args); - } - - private bool ShouldBreak(SectionFormatOption formatOption) - { - return formatOption.HasFlag(SectionFormatOption.LineBreakAfterHeader); - } - - private void AddParameter(MamlParameter parameter, MamlCommand command) - { - var extraNewLine = ShouldBreak(parameter.FormatOption); - - AddHeader(ModelTransformerBase.PARAMETERSET_NAME_HEADING_LEVEL, '-' + parameter.Name, extraNewLine: extraNewLine); - - AddParagraphs(parameter.Description); - - var sets = SimplifyParamSets(GetParamSetDictionary(parameter.Name, command.Syntax)); - foreach (var set in sets) - { - _stringBuilder.AppendFormat("```yaml{0}", NewLine); - - AppendYamlKeyValue(MarkdownStrings.Type, parameter.Type); - - string parameterSetsString; - if (command.Syntax.Count == 1 || set.Item1.Count == command.Syntax.Count) - { - // ignore, if there is just one parameter set - // or this parameter belongs to All parameter sets, use (All) - parameterSetsString = ModelTransformerVersion2.ALL_PARAM_SETS_MONIKER; - } - else - { - parameterSetsString = JoinWithComma(set.Item1); - } - - AppendYamlKeyValue(MarkdownStrings.Parameter_Sets, parameterSetsString); - - AppendYamlKeyValue(MarkdownStrings.Aliases, JoinWithComma(parameter.Aliases)); - if (parameter.ParameterValueGroup.Count > 0) - { - AppendYamlKeyValue(MarkdownStrings.Accepted_values, JoinWithComma(parameter.ParameterValueGroup)); - } - - if (parameter.Applicable != null) - { - AppendYamlKeyValue(MarkdownStrings.Applicable, JoinWithComma(parameter.Applicable)); - } - - _stringBuilder.AppendLine(); - - AppendYamlKeyValue(MarkdownStrings.Required, set.Item2.Required.ToString()); - AppendYamlKeyValue(MarkdownStrings.Position, set.Item2.IsNamed() ? "Named" : set.Item2.Position); - AppendYamlKeyValue(MarkdownStrings.Default_value, string.IsNullOrWhiteSpace(parameter.DefaultValue) ? "None" : parameter.DefaultValue); - AppendYamlKeyValue(MarkdownStrings.Accept_pipeline_input, parameter.PipelineInput); - AppendYamlKeyValue(MarkdownStrings.Accept_wildcard_characters, parameter.Globbing.ToString()); - - _stringBuilder.AppendFormat("```{0}{0}", NewLine); - } - } - - private void AppendYamlKeyValue(string key, string value) - { - if (string.IsNullOrEmpty(value)) - { - _stringBuilder.AppendFormat("{0}:{1}", key, NewLine); - - return; - } - - _stringBuilder.AppendFormat("{0}: {1}{2}", key, value, NewLine); - } - - private void AddExamples(MamlCommand command) - { - AddHeader(ModelTransformerBase.COMMAND_ENTRIES_HEADING_LEVEL, MarkdownStrings.EXAMPLES); - foreach (var example in command.Examples) - { - var extraNewLine = ShouldBreak(example.FormatOption); - - AddHeader(ModelTransformerBase.EXAMPLE_HEADING_LEVEL, GetExampleTitle(example.Title), extraNewLine: extraNewLine); - - if (!string.IsNullOrEmpty(example.Introduction)) - { - AddParagraphs(example.Introduction); - } - - if (example.Code != null) - { - for (var i = 0; i < example.Code.Length; i++) - { - AddCodeSnippet(example.Code[i].Text, example.Code[i].LanguageMoniker); - } - } - - if (!string.IsNullOrEmpty(example.Remarks)) - { - AddParagraphs(example.Remarks); - } - } - } - - private static string GetExampleTitle(string title) - { - var match = Regex.Match(title, @"^(-| ){0,}(?([^\f\n\r\t\v\x85\p{Z}-][^\f\n\r\t\v\x85]+[^\f\n\r\t\v\x85\p{Z}-]))(-| ){0,}$"); - - if (match.Success) - { - return match.Groups["title"].Value; - } - - return title; - } - - public static string GetSyntaxString(MamlCommand command, MamlSyntax syntax) - { - return GetSyntaxString(command, syntax, DEFAULT_SYNTAX_WIDTH); - } - - public static string GetSyntaxString(MamlCommand command, MamlSyntax syntax, int maxSyntaxWidth) - { - // TODO: we may want to add ParameterValueGroup info here, - // but it's fine for now - - var sb = new StringBuilder(); - sb.Append(command.Name); - - var paramStrings = new List<string>(); - - // first we create list of param string we want to add - foreach (var param in syntax.Parameters) - { - string paramStr; - if (param.IsSwitchParameter()) - { - paramStr = string.Format("[-{0}]", param.Name); - } - else - { - paramStr = string.Format("-{0}", param.Name); - if (!param.IsNamed()) - { - // for positional parameters, we can avoid specifying the name - paramStr = string.Format("[{0}]", paramStr); - } - - paramStr = string.Format("{0} <{1}>", paramStr, param.Type); - if (!param.Required) - { - paramStr = string.Format("[{0}]", paramStr); - } - } - paramStrings.Add(paramStr); - } - - if (command.IsWorkflow) - { - paramStrings.Add("[<" + MarkdownStrings.WorkflowParametersToken + ">]"); - } - - if (command.SupportCommonParameters) - { - paramStrings.Add("[<" + MarkdownStrings.CommonParametersToken + ">]"); - } - - // then we format them properly with repsect to max width for window. - int widthBeforeLastBreak = 0; - foreach (string paramStr in paramStrings) { - - if (sb.Length - widthBeforeLastBreak + paramStr.Length > maxSyntaxWidth) - { - sb.AppendLine(); - widthBeforeLastBreak = sb.Length; - } - - sb.AppendFormat(" {0}", paramStr); - } - - return sb.ToString(); - } - - private void AddSyntax(MamlCommand command) - { - AddHeader(ModelTransformerBase.COMMAND_ENTRIES_HEADING_LEVEL, MarkdownStrings.SYNTAX); - foreach (var syntax in command.Syntax) - { - if (command.Syntax.Count > 1) - { - AddHeader(ModelTransformerBase.PARAMETERSET_NAME_HEADING_LEVEL, string.Format("{0}{1}",syntax.ParameterSetName,syntax.IsDefault ? MarkdownStrings.DefaultParameterSetModifier : null), extraNewLine: false); - } - - AddCodeSnippet(GetSyntaxString(command, syntax)); - } - } - - private void AddEntryHeaderWithText(string header, SectionBody body) - { - var extraNewLine = body == null || string.IsNullOrEmpty(body.Text) || ShouldBreak(body.FormatOption); - - // Add header - AddHeader(ModelTransformerBase.COMMAND_ENTRIES_HEADING_LEVEL, header, extraNewLine: extraNewLine); - - // to correctly handle empty text case, we are adding new-line here - if (body != null && !string.IsNullOrEmpty(body.Text)) - { - AddParagraphs(body.Text); - } - } - - private void AddCodeSnippet(string code, string lang = "") - { - _stringBuilder.AppendFormat("```{1}{2}{0}{2}```{2}{2}", code, lang, NewLine); - } - - private void AddHeader(int level, string header, bool extraNewLine = true) - { - for (int i = 0; i < level; i++) - { - _stringBuilder.Append('#'); - } - _stringBuilder.Append(' '); - _stringBuilder.AppendFormat("{0}{1}", header, NewLine); - if (extraNewLine) - { - _stringBuilder.Append(NewLine); - } - } - - private string GetAutoWrappingForNonListLine(string line) - { - return Regex.Replace(line, @"([\.\!\?]) ( )*([^\r\n])", "$1$2\r\n$3"); - } - - private string GetAutoWrappingForMarkdown(string[] lines) - { - // this is an implementation of https://github.com/PowerShell/platyPS/issues/93 - - // algorithm: identify chunks that represent lists - // Every entry in a list should be preserved as is and 1 EOL between them - // Every entry not in a list should be split with GetAutoWrappingForNonListLine - // delimiters between lists and non-lists are 2 EOLs. - - var newLines = new List<string>(); - - for (int i = 0; i < lines.Length; i++) - { - if (MarkdownParser.HasListPrefix(lines[i])) - { - if (i > 0 && !MarkdownParser.HasListPrefix(lines[i - 1])) - { - // we are in a list and it just started - newLines.Add(NewLine + lines[i]); - } - else - { - newLines.Add(lines[i]); - } - } - else - { - if (i > 0) - { - // we are just finished a list - newLines.Add(NewLine + GetAutoWrappingForNonListLine(lines[i])); - } - else - { - newLines.Add(GetAutoWrappingForNonListLine(lines[i])); - } - } - } - - return string.Join(NewLine, newLines); - } - - private void AddParagraphs(string body, bool noNewLines = false, bool skipAutoWrap = false) - { - if (string.IsNullOrWhiteSpace(body)) - { - return; - } - - if (this._mode != ParserMode.FormattingPreserve && skipAutoWrap != true) - { - string[] paragraphs = body.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); - body = GetAutoWrappingForMarkdown(paragraphs.Select(para => GetEscapedMarkdownText(para.Trim())).ToArray()); - } - - // The the body already ended in a line break don't add extra lines on to the end - if (body.EndsWith("\r\n\r\n")) - { - noNewLines = true; - } - - _stringBuilder.AppendFormat("{0}{1}{1}", body, noNewLines ? null : NewLine); - } - - private static string BackSlashMatchEvaluater(Match match) - { - // '\<' -> '\\<' - // '\\<' -> '\\<' - noop - // '\\\<' -> '\\\\<' - - var g1 = match.Groups[1].Value; - var g2 = match.Groups[2].Value[0]; - - if (g1.Length % 2 == 0 && "<>()[]`".Contains(g2)) - { - return @"\" + match.Value; - } - - return match.Value; - } - - // public just to make testing easier - public static string GetEscapedMarkdownText(string text) - { - // this is kind of a crazy replacement to handle escaping properly. - // we need to do the reverse operation in our markdown parser. - - // PS code: (((($text - replace '\\\\','\\\\') -replace '([<>])','\$1') -replace '\\([\[\]\(\)])', '\\$1') - - // examples: - // '\<' -> '\\\<' - // '\' -> '\' - // '\\' -> '\\\\' - // '<' -> '\<' - - text = text - .Replace(@"\\", @"\\\\"); - - text = Regex.Replace(text, @"(\\*)\\(.)", new MatchEvaluator(BackSlashMatchEvaluater)); - - return text - .Replace(@"<", @"\<") - .Replace(@">", @"\>") - - .Replace(@"[", @"\[") - .Replace(@"]", @"\]") - // per https://github.com/PowerShell/platyPS/issues/121 we don't perform escaping for () in markdown renderer, but we do in the parser - //.Replace(@"(", @"\(") - //.Replace(@")", @"\)") - .Replace(@"`", @"\`"); - } - } -} diff --git a/v1/src/Markdown.MAML/Renderer/RenderCleaner.cs b/v1/src/Markdown.MAML/Renderer/RenderCleaner.cs deleted file mode 100644 index 4e118a5b..00000000 --- a/v1/src/Markdown.MAML/Renderer/RenderCleaner.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System.Text.RegularExpressions; - -namespace Markdown.MAML.Renderer -{ - internal static class RenderCleaner - { - /// <summary> - /// This method runs all of the normalization tools in the cleaner. This allows full normalization without needing to call - /// each and every method on a string. - /// </summary> - /// <param name="text">The string that needs to be cleaned.</param> - /// <returns>Normalizaed string: WhiteSpaces, Quotes and Dashes, Linebreaks</returns> - public static string FullNormalization(string text) - { - return NormalizeQuotesAndDashes( - NormalizeLineBreaks( - NormalizeWhitespaces(text))); - } - - public static string NormalizeWhitespaces(string text) - { - // there are many spaces - // https://www.cs.tut.fi/~jkorpela/chars/spaces.html - // we interested in just a few of them. - // Also, we use en-space \uc2a0 for tabulation inside NOTES list, when we convert them into lists. - // it's a hack, this characte is not a whitespace, but that's how we work-around help engine limitations. - text = text - // non-breakable white-space to a normal one - .Replace('\u00a0', ' ') - .Replace('\uc2a0', ' ') - // also try to clean up these ACSII characters - .Replace("Â ", " ") - .Replace('Ã', ' ') - ; - - return text; - } - - public static string NormalizeQuotesAndDashes(string text) - { - // NOTE: quotes has left, right + low and reversed variants - // we don't normalize a low-single one, because it could be treated as comma - - // single quote - text = Regex.Replace(text, "\u2018|\u2019|\u201b", "\'"); - - // double quote - text = Regex.Replace(text, "\u201c|\u201d|\u201e|\u201f", "\""); - - // there are 100500 dashes types in unicode https://www.cs.tut.fi/~jkorpela/dashes.html - // we want to normalize at least the most commonly used - text = Regex.Replace(text, "\u05be|\u1806|\u2010|\u2011|\u00AD|\u2012|\u2013|\u2014|\u2015|\u2212", "-"); - - return text; - } - - public static string NormalizeLineBreaks(string text) - { - return Regex.Replace(text, "\r\n?|\n", "\r\n"); - } - } -} diff --git a/v1/src/Markdown.MAML/Renderer/TextRenderer.cs b/v1/src/Markdown.MAML/Renderer/TextRenderer.cs deleted file mode 100644 index a8afaf0a..00000000 --- a/v1/src/Markdown.MAML/Renderer/TextRenderer.cs +++ /dev/null @@ -1,183 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using Markdown.MAML.Model.Markdown; -using Markdown.MAML.Resources; - -namespace Markdown.MAML.Renderer -{ - public class TextRenderer - { - private StringBuilder _stringBuilder = new StringBuilder(); - - private const string AboutIndentation = " "; - - private const string NewLine = "\r\n"; - - private int _maxLineWidth { get; set; } - - public TextRenderer() : this(80) { } - - public TextRenderer(int maxLineWidth) - { - _maxLineWidth = maxLineWidth; - } - - public string AboutMarkdownToString(DocumentNode document) - { - //ensure that all node types in the about topic are handeled. - var acceptableNodeTypes = new List<MarkdownNodeType> - { - MarkdownNodeType.Heading, - MarkdownNodeType.Paragraph, - MarkdownNodeType.CodeBlock - }; - if (document.Children.Any(c => (!acceptableNodeTypes.Contains(c.NodeType)))) - { - throw new NotSupportedException("About Topics can only have heading, parapgrah or code block nodes in their Markdown Model."); - } - - //processes all nodes in order - foreach (var currentNode in document.Children) - { - switch (currentNode.NodeType) - { - case MarkdownNodeType.Paragraph: - ParagraphNode paragraphNode = currentNode as ParagraphNode; - AddAboutParagraph(paragraphNode); - break; - case MarkdownNodeType.Heading: - HeadingNode headingNode = currentNode as HeadingNode; - AddAboutHeading(headingNode, document); - break; - case MarkdownNodeType.CodeBlock: - CodeBlockNode codeblockNode = currentNode as CodeBlockNode; - AddAboutCodeBlock(codeblockNode); - break; - default: - throw new ArgumentOutOfRangeException(); - } - } - - return RenderCleaner.FullNormalization(_stringBuilder.ToString()); - } - - private void AddAboutCodeBlock(CodeBlockNode codeblockNode) - { - var lines = codeblockNode.Text.Split(new[] {"\r\n"}, StringSplitOptions.None); - - foreach (var line in lines) - { - _stringBuilder.Append(AboutIndentation); - _stringBuilder.AppendLine(line); - } - - _stringBuilder.AppendLine(); - } - - private void AddAboutHeading(HeadingNode headingNode, DocumentNode document) - { - const int level1Heading = 1; - const int level2Heading = 2; - - if (document.Children.ElementAt(0) as HeadingNode == headingNode) - { - _stringBuilder.AppendLine(MarkdownStrings.AboutTopicFirstHeader.ToUpper()); - } - else if (headingNode.HeadingLevel == level1Heading) - { - _stringBuilder.AppendLine(headingNode.Text.ToUpper()); - } - else if (headingNode.HeadingLevel == level2Heading && document.Children.ElementAt(1) == headingNode) - { - _stringBuilder.AppendFormat("{0}{1}{2}{3}", AboutIndentation, headingNode.Text.ToLower(), NewLine, NewLine); - } - else if (headingNode.HeadingLevel == level2Heading) - { - _stringBuilder.AppendLine(headingNode.Text); - } - else - { - _stringBuilder.AppendFormat("{0}{1}{2}", AboutIndentation, headingNode.Text.ToUpper(), NewLine); - } - } - - private void AddAboutParagraph(ParagraphNode paragraphNode) - { - foreach (var lineContent in paragraphNode.Spans.Select(span => span.Text)) - { - //handles all paragraph lines over 80 characters long and not headers - if (lineContent.Length > _maxLineWidth - 4) - { - WrapAndAppendLines(lineContent, _stringBuilder); - _stringBuilder.AppendLine(); - } - else if (StringComparer.OrdinalIgnoreCase.Equals(lineContent, "\n")) - { - _stringBuilder.AppendLine(); - } - else - { - _stringBuilder.AppendFormat("{0}{1}{2}", AboutIndentation, lineContent, NewLine); - } - } - _stringBuilder.AppendLine(); - } - - public void WrapAndAppendLines(string text, StringBuilder sb) - { - const string singleSpace = " "; - - var words = text.Split(' '); - text = ""; - - foreach (var word in words) - { - if (word.Contains("\r\n")) - { - var breakLine = word.Split(new[] {"\r\n"}, StringSplitOptions.RemoveEmptyEntries); - - foreach (var part in breakLine) - { - if (part == breakLine.Last()) - { - text += part + singleSpace; - } - else - { - text += part; - sb.AppendFormat("{0}{1}{2}", AboutIndentation, text, NewLine); - text = ""; - } - } - } - else if (text.Length + word.Length > (_maxLineWidth - 4)) - { - if (StringComparer.OrdinalIgnoreCase.Equals(text.Substring(text.Length - 1), singleSpace)) - { - text = text.Substring(0, text.Length - 1); - } - sb.AppendFormat("{0}{1}{2}", AboutIndentation, text, NewLine); - - text = word + singleSpace; - } - else - { - text += word + singleSpace; - } - } - - if (text.Length <= 0 || StringComparer.OrdinalIgnoreCase.Equals(text, singleSpace)) - { - return; - } - if (StringComparer.OrdinalIgnoreCase.Equals(text.Substring(text.Length - 1), singleSpace)) - { - text = text.Substring(0, text.Length - 1); - } - - sb.AppendFormat("{0}{1}", AboutIndentation, text); - } - } -} diff --git a/v1/src/Markdown.MAML/Renderer/YamlRenderer.cs b/v1/src/Markdown.MAML/Renderer/YamlRenderer.cs deleted file mode 100644 index f85000ab..00000000 --- a/v1/src/Markdown.MAML/Renderer/YamlRenderer.cs +++ /dev/null @@ -1,97 +0,0 @@ -using Markdown.MAML.Model.MAML; -using Markdown.MAML.Model.YAML; -using System.IO; -using System.Linq; -using YamlDotNet.Serialization; -using YamlDotNet.Serialization.NamingConventions; - -namespace Markdown.MAML.Renderer -{ - public class YamlRenderer - { - public static string MamlModelToString(MamlCommand mamlCommand) - { - var serializer = new SerializerBuilder() - .WithNamingConvention(new CamelCaseNamingConvention()) - .Build(); - - var model = new YamlCommand - { - Name = mamlCommand.Name, - Notes = mamlCommand.Notes.Text, - Remarks = mamlCommand.Description.Text, - Summary = mamlCommand.Synopsis.Text, - Examples = mamlCommand.Examples.Select(CreateExample).ToList(), - Inputs = mamlCommand.Inputs.Select(CreateInputOutput).ToList(), - Links = mamlCommand.Links.Select(CreateLink).ToList(), - Module = new YamlModule { Name = mamlCommand.ModuleName }, - OptionalParameters = mamlCommand.Parameters.Where(p => !p.Required).Select(CreateParameter).ToList(), - Outputs = mamlCommand.Outputs.Select(CreateInputOutput).ToList(), - RequiredParameters = mamlCommand.Parameters.Where(p => p.Required).Select(CreateParameter).ToList(), - Syntaxes = mamlCommand.Syntax.Select(CreateSyntax).ToList() - }; - - using (var writer = new StringWriter()) - { - serializer.Serialize(writer, model); - writer.Flush(); - return writer.ToString(); - } - } - - private static YamlExample CreateExample(MamlExample mamlExample) - { - return new YamlExample - { - Name = mamlExample.Title, - PreCode = mamlExample.Introduction, - Code = string.Join("\r\n\r\n", mamlExample.Code.Select(block => block.Text)), - PostCode = mamlExample.Remarks - }; - } - - private static YamlInputOutput CreateInputOutput(MamlInputOutput mamlInputOutput) - { - return new YamlInputOutput - { - Description = mamlInputOutput.Description, - Type = mamlInputOutput.TypeName - }; - } - - private static YamlLink CreateLink(MamlLink mamlLink) - { - return new YamlLink - { - Href = mamlLink.LinkUri, - Text = mamlLink.LinkName - }; - } - - private static YamlParameter CreateParameter(MamlParameter mamlParameter) - { - return new YamlParameter - { - Name = mamlParameter.Name, - AcceptWildcardCharacters = mamlParameter.Globbing, - Description = mamlParameter.Description, - Aliases = mamlParameter.Aliases.ToList(), - Type = mamlParameter.Type, - ParameterValueGroup = mamlParameter.ParameterValueGroup, - Position = mamlParameter.Position, - PipelineInput = mamlParameter.PipelineInput, - DefaultValue = mamlParameter.DefaultValue - }; - } - - private static YamlSyntax CreateSyntax(MamlSyntax syntax) - { - return new YamlSyntax - { - IsDefault = syntax.IsDefault, - ParameterValueGroup = syntax.ParameterSetName, - Parameters = syntax.Parameters.Select(p => p.Name).ToList() - }; - } - } -} diff --git a/v1/src/Markdown.MAML/Resources/MarkdownStrings.Designer.cs b/v1/src/Markdown.MAML/Resources/MarkdownStrings.Designer.cs deleted file mode 100644 index 5dc04642..00000000 --- a/v1/src/Markdown.MAML/Resources/MarkdownStrings.Designer.cs +++ /dev/null @@ -1,289 +0,0 @@ -//------------------------------------------------------------------------------ -// <auto-generated> -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// </auto-generated> -//------------------------------------------------------------------------------ - -namespace Markdown.MAML.Resources { - using System; - using System.Reflection; - - - /// <summary> - /// A strongly-typed resource class, for looking up localized strings, etc. - /// </summary> - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class MarkdownStrings { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal MarkdownStrings() { - } - - /// <summary> - /// Returns the cached ResourceManager instance used by this class. - /// </summary> - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Markdown.MAML.Resources.MarkdownStrings", typeof(MarkdownStrings).GetTypeInfo().Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// <summary> - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// </summary> - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// <summary> - /// Looks up a localized string similar to TOPIC. - /// </summary> - internal static string AboutTopicFirstHeader { - get { - return ResourceManager.GetString("AboutTopicFirstHeader", resourceCulture); - } - } - - /// <summary> - /// Looks up a localized string similar to Accept pipeline input. - /// </summary> - internal static string Accept_pipeline_input { - get { - return ResourceManager.GetString("Accept_pipeline_input", resourceCulture); - } - } - - /// <summary> - /// Looks up a localized string similar to Accept wildcard characters. - /// </summary> - internal static string Accept_wildcard_characters { - get { - return ResourceManager.GetString("Accept_wildcard_characters", resourceCulture); - } - } - - /// <summary> - /// Looks up a localized string similar to Accepted values. - /// </summary> - internal static string Accepted_values { - get { - return ResourceManager.GetString("Accepted_values", resourceCulture); - } - } - - /// <summary> - /// Looks up a localized string similar to Aliases. - /// </summary> - internal static string Aliases { - get { - return ResourceManager.GetString("Aliases", resourceCulture); - } - } - - /// <summary> - /// Looks up a localized string similar to Applicable. - /// </summary> - internal static string Applicable { - get { - return ResourceManager.GetString("Applicable", resourceCulture); - } - } - - /// <summary> - /// Looks up a localized string similar to This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - /// </summary> - internal static string CommonParametersText { - get { - return ResourceManager.GetString("CommonParametersText", resourceCulture); - } - } - - /// <summary> - /// Looks up a localized string similar to CommonParameters. - /// </summary> - internal static string CommonParametersToken { - get { - return ResourceManager.GetString("CommonParametersToken", resourceCulture); - } - } - - /// <summary> - /// Looks up a localized string similar to Default value. - /// </summary> - internal static string Default_value { - get { - return ResourceManager.GetString("Default_value", resourceCulture); - } - } - - /// <summary> - /// Looks up a localized string similar to (Default). - /// </summary> - internal static string DefaultParameterSetModifier { - get { - return ResourceManager.GetString("DefaultParameterSetModifier", resourceCulture); - } - } - - /// <summary> - /// Looks up a localized string similar to DESCRIPTION. - /// </summary> - internal static string DESCRIPTION { - get { - return ResourceManager.GetString("DESCRIPTION", resourceCulture); - } - } - - /// <summary> - /// Looks up a localized string similar to EXAMPLES. - /// </summary> - internal static string EXAMPLES { - get { - return ResourceManager.GetString("EXAMPLES", resourceCulture); - } - } - - /// <summary> - /// Looks up a localized string similar to INPUTS. - /// </summary> - internal static string INPUTS { - get { - return ResourceManager.GetString("INPUTS", resourceCulture); - } - } - - /// <summary> - /// Looks up a localized string similar to NOTES. - /// </summary> - internal static string NOTES { - get { - return ResourceManager.GetString("NOTES", resourceCulture); - } - } - - /// <summary> - /// Looks up a localized string similar to OUTPUTS. - /// </summary> - internal static string OUTPUTS { - get { - return ResourceManager.GetString("OUTPUTS", resourceCulture); - } - } - - /// <summary> - /// Looks up a localized string similar to Parameter Sets. - /// </summary> - internal static string Parameter_Sets { - get { - return ResourceManager.GetString("Parameter_Sets", resourceCulture); - } - } - - /// <summary> - /// Looks up a localized string similar to PARAMETERS. - /// </summary> - internal static string PARAMETERS { - get { - return ResourceManager.GetString("PARAMETERS", resourceCulture); - } - } - - /// <summary> - /// Looks up a localized string similar to Position. - /// </summary> - internal static string Position { - get { - return ResourceManager.GetString("Position", resourceCulture); - } - } - - /// <summary> - /// Looks up a localized string similar to RELATED LINKS. - /// </summary> - internal static string RELATED_LINKS { - get { - return ResourceManager.GetString("RELATED_LINKS", resourceCulture); - } - } - - /// <summary> - /// Looks up a localized string similar to Required. - /// </summary> - internal static string Required { - get { - return ResourceManager.GetString("Required", resourceCulture); - } - } - - /// <summary> - /// Looks up a localized string similar to SYNOPSIS. - /// </summary> - internal static string SYNOPSIS { - get { - return ResourceManager.GetString("SYNOPSIS", resourceCulture); - } - } - - /// <summary> - /// Looks up a localized string similar to SYNTAX. - /// </summary> - internal static string SYNTAX { - get { - return ResourceManager.GetString("SYNTAX", resourceCulture); - } - } - - /// <summary> - /// Looks up a localized string similar to Type. - /// </summary> - internal static string Type { - get { - return ResourceManager.GetString("Type", resourceCulture); - } - } - - /// <summary> - /// Looks up a localized string similar to This cmdlet supports the following workflow common parameters: -PSParameterCollection, -PSComputerName, -PSCredential, -PSConnectionRetryCount, -PSConnectionRetryIntervalSec, -PSRunningTimeoutSec, -PSElapsedTimeoutSec, -PSPersist, -PSAuthentication, -PSAuthenticationLevel, -PSApplicationName, -PSPort, -PSUseSSL, -PSConfigurationName, -PSConnectionURI, -PSAllowRedirection, -PSSessionOption, -PSCertificateThumbprint, -PSPrivateMetadata, -AsJob, -JobName, and –InputObject. For more information, see about_Workf [rest of string was truncated]";. - /// </summary> - internal static string WorkflowParametersText { - get { - return ResourceManager.GetString("WorkflowParametersText", resourceCulture); - } - } - - /// <summary> - /// Looks up a localized string similar to WorkflowCommonParameters. - /// </summary> - internal static string WorkflowParametersToken { - get { - return ResourceManager.GetString("WorkflowParametersToken", resourceCulture); - } - } - } -} diff --git a/v1/src/Markdown.MAML/Resources/MarkdownStrings.resx b/v1/src/Markdown.MAML/Resources/MarkdownStrings.resx deleted file mode 100644 index 70603e76..00000000 --- a/v1/src/Markdown.MAML/Resources/MarkdownStrings.resx +++ /dev/null @@ -1,195 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<root> - <!-- - Microsoft ResX Schema - - Version 2.0 - - The primary goals of this format is to allow a simple XML format - that is mostly human readable. The generation and parsing of the - various data types are done through the TypeConverter classes - associated with the data types. - - Example: - - ... ado.net/XML headers & schema ... - <resheader name="resmimetype">text/microsoft-resx</resheader> - <resheader name="version">2.0</resheader> - <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> - <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> - <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> - <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> - <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> - <value>[base64 mime encoded serialized .NET Framework object]</value> - </data> - <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> - <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> - <comment>This is a comment</comment> - </data> - - There are any number of "resheader" rows that contain simple - name/value pairs. - - Each data row contains a name, and value. The row also contains a - type or mimetype. Type corresponds to a .NET class that support - text/value conversion through the TypeConverter architecture. - Classes that don't support this are serialized and stored with the - mimetype set. - - The mimetype is used for serialized objects, and tells the - ResXResourceReader how to depersist the object. This is currently not - extensible. For a given mimetype the value must be set accordingly: - - Note - application/x-microsoft.net.object.binary.base64 is the format - that the ResXResourceWriter will generate, however the reader can - read any of the formats listed below. - - mimetype: application/x-microsoft.net.object.binary.base64 - value : The object must be serialized with - : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter - : and then encoded with base64 encoding. - - mimetype: application/x-microsoft.net.object.soap.base64 - value : The object must be serialized with - : System.Runtime.Serialization.Formatters.Soap.SoapFormatter - : and then encoded with base64 encoding. - - mimetype: application/x-microsoft.net.object.bytearray.base64 - value : The object must be serialized into a byte array - : using a System.ComponentModel.TypeConverter - : and then encoded with base64 encoding. - --> - <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> - <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> - <xsd:element name="root" msdata:IsDataSet="true"> - <xsd:complexType> - <xsd:choice maxOccurs="unbounded"> - <xsd:element name="metadata"> - <xsd:complexType> - <xsd:sequence> - <xsd:element name="value" type="xsd:string" minOccurs="0" /> - </xsd:sequence> - <xsd:attribute name="name" use="required" type="xsd:string" /> - <xsd:attribute name="type" type="xsd:string" /> - <xsd:attribute name="mimetype" type="xsd:string" /> - <xsd:attribute ref="xml:space" /> - </xsd:complexType> - </xsd:element> - <xsd:element name="assembly"> - <xsd:complexType> - <xsd:attribute name="alias" type="xsd:string" /> - <xsd:attribute name="name" type="xsd:string" /> - </xsd:complexType> - </xsd:element> - <xsd:element name="data"> - <xsd:complexType> - <xsd:sequence> - <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> - <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> - </xsd:sequence> - <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> - <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> - <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> - <xsd:attribute ref="xml:space" /> - </xsd:complexType> - </xsd:element> - <xsd:element name="resheader"> - <xsd:complexType> - <xsd:sequence> - <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> - </xsd:sequence> - <xsd:attribute name="name" type="xsd:string" use="required" /> - </xsd:complexType> - </xsd:element> - </xsd:choice> - </xsd:complexType> - </xsd:element> - </xsd:schema> - <resheader name="resmimetype"> - <value>text/microsoft-resx</value> - </resheader> - <resheader name="version"> - <value>2.0</value> - </resheader> - <resheader name="reader"> - <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> - </resheader> - <resheader name="writer"> - <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> - </resheader> - <data name="Accept_pipeline_input" xml:space="preserve"> - <value>Accept pipeline input</value> - </data> - <data name="Accept_wildcard_characters" xml:space="preserve"> - <value>Accept wildcard characters</value> - </data> - <data name="Aliases" xml:space="preserve"> - <value>Aliases</value> - </data> - <data name="Default_value" xml:space="preserve"> - <value>Default value</value> - </data> - <data name="DESCRIPTION" xml:space="preserve"> - <value>DESCRIPTION</value> - </data> - <data name="EXAMPLES" xml:space="preserve"> - <value>EXAMPLES</value> - </data> - <data name="INPUTS" xml:space="preserve"> - <value>INPUTS</value> - </data> - <data name="OUTPUTS" xml:space="preserve"> - <value>OUTPUTS</value> - </data> - <data name="PARAMETERS" xml:space="preserve"> - <value>PARAMETERS</value> - </data> - <data name="Parameter_Sets" xml:space="preserve"> - <value>Parameter Sets</value> - </data> - <data name="Position" xml:space="preserve"> - <value>Position</value> - </data> - <data name="RELATED_LINKS" xml:space="preserve"> - <value>RELATED LINKS</value> - </data> - <data name="Required" xml:space="preserve"> - <value>Required</value> - </data> - <data name="SYNOPSIS" xml:space="preserve"> - <value>SYNOPSIS</value> - </data> - <data name="SYNTAX" xml:space="preserve"> - <value>SYNTAX</value> - </data> - <data name="Type" xml:space="preserve"> - <value>Type</value> - </data> - <data name="Accepted_values" xml:space="preserve"> - <value>Accepted values</value> - </data> - <data name="NOTES" xml:space="preserve"> - <value>NOTES</value> - </data> - <data name="CommonParametersText" xml:space="preserve"> - <value>This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).</value> - </data> - <data name="CommonParametersToken" xml:space="preserve"> - <value>CommonParameters</value> - </data> - <data name="WorkflowParametersText" xml:space="preserve"> - <value>This cmdlet supports the following workflow common parameters: -PSParameterCollection, -PSComputerName, -PSCredential, -PSConnectionRetryCount, -PSConnectionRetryIntervalSec, -PSRunningTimeoutSec, -PSElapsedTimeoutSec, -PSPersist, -PSAuthentication, -PSAuthenticationLevel, -PSApplicationName, -PSPort, -PSUseSSL, -PSConfigurationName, -PSConnectionURI, -PSAllowRedirection, -PSSessionOption, -PSCertificateThumbprint, -PSPrivateMetadata, -AsJob, -JobName, and –InputObject. For more information, see [about_WorkflowCommonParameters](http://go.microsoft.com/fwlink/p/?LinkID=533952).</value> - </data> - <data name="WorkflowParametersToken" xml:space="preserve"> - <value>WorkflowCommonParameters</value> - </data> - <data name="DefaultParameterSetModifier" xml:space="preserve"> - <value> (Default)</value> - </data> - <data name="AboutTopicFirstHeader" xml:space="preserve"> - <value>TOPIC</value> - </data> - <data name="Applicable" xml:space="preserve"> - <value>Applicable</value> - </data> -</root> \ No newline at end of file diff --git a/v1/src/Markdown.MAML/Transformer/HelpSchemaException.cs b/v1/src/Markdown.MAML/Transformer/HelpSchemaException.cs deleted file mode 100644 index 866ce70c..00000000 --- a/v1/src/Markdown.MAML/Transformer/HelpSchemaException.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using Markdown.MAML.Model.Markdown; - -namespace Markdown.MAML.Transformer -{ - public class HelpSchemaException : ArgumentException - { - private static string GetSnippet(string input) - { - if (input.Length < 50) - { - return input; - } - return input.Substring(0, 50) + "..."; - } - - public HelpSchemaException(SourceExtent extent, string message) - : base( - String.Format( - "{0}:{1}:({2}) '{3}'\n {4}", - extent.File, - extent.Line.Start, - extent.Column.Start, - GetSnippet(extent.OriginalText), - message) - ) - { - } - } -} diff --git a/v1/src/Markdown.MAML/Transformer/IModelTransformer.cs b/v1/src/Markdown.MAML/Transformer/IModelTransformer.cs deleted file mode 100644 index bb335407..00000000 --- a/v1/src/Markdown.MAML/Transformer/IModelTransformer.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.Collections.Generic; -using Markdown.MAML.Model.MAML; -using Markdown.MAML.Model.Markdown; - -namespace Markdown.MAML.Transformer -{ - public interface IModelTransformer - { - IEnumerable<MamlCommand> NodeModelToMamlModel(DocumentNode node); - } -} \ No newline at end of file diff --git a/v1/src/Markdown.MAML/Transformer/MamlComparer.cs b/v1/src/Markdown.MAML/Transformer/MamlComparer.cs deleted file mode 100644 index d48ac6c4..00000000 --- a/v1/src/Markdown.MAML/Transformer/MamlComparer.cs +++ /dev/null @@ -1,83 +0,0 @@ -using Markdown.MAML.Model.MAML; -using System.Collections.Generic; - -namespace Markdown.MAML.Transformer -{ - internal class MamlSyntaxNameComparer : IComparer<MamlSyntax> - { - public int Compare(MamlSyntax x, MamlSyntax y) - { - return string.Compare(x.ParameterSetName.ToUpper(), y.ParameterSetName.ToUpper()); - } - } - - internal class MamlParameterNameComparer : IComparer<MamlParameter> - { - public int Compare(MamlParameter x, MamlParameter y) - { - return string.Compare(x.Name.ToUpper(), y.Name.ToUpper()); - } - } - - internal class MamlParameterAttributeComparer : IComparer<MamlParameter> - { - public int Compare(MamlParameter x, MamlParameter y) - { - var match = x.Name == y.Name; - - if ( - (x.Required != y.Required) || - (x.Aliases != y.Aliases) || - (x.DefaultValue != y.DefaultValue) || - (x.Position != y.Position) || - (x.Type != y.Type) || - (x.PipelineInput != y.PipelineInput) || - (x.AttributesMetadata != y.AttributesMetadata) - ) - { - match = false; - } - - if (match) - { - return 0; - } - - return -1; - } - } - - internal class MamlParameterEqualityComparer : IEqualityComparer<MamlParameter> - { - public bool Equals(MamlParameter x, MamlParameter y) - { - return x.Name == y.Name; - } - - public int GetHashCode(MamlParameter obj) - { - if (obj == null || obj.Name == null) - { - return 0; - } - return obj.Name.ToUpper().GetHashCode(); - } - } - - internal class MamlParameterSetEqualityComparer : IEqualityComparer<MamlSyntax> - { - public bool Equals(MamlSyntax x, MamlSyntax y) - { - return x.ParameterSetName == y.ParameterSetName; - } - - public int GetHashCode(MamlSyntax obj) - { - if (obj == null || obj.ParameterSetName == null) - { - return 0; - } - return obj.ParameterSetName.ToUpper().GetHashCode(); - } - } -} \ No newline at end of file diff --git a/v1/src/Markdown.MAML/Transformer/MamlModelMerger.cs b/v1/src/Markdown.MAML/Transformer/MamlModelMerger.cs deleted file mode 100644 index 0ce0918e..00000000 --- a/v1/src/Markdown.MAML/Transformer/MamlModelMerger.cs +++ /dev/null @@ -1,286 +0,0 @@ -using Markdown.MAML.Model.MAML; -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Markdown.MAML.Transformer -{ - public class MamlModelMerger - { - private Action<string> _infoCallback; - - private bool _cmdletUpdated; - - public MamlModelMerger() : this(null) { } - - /// <summary> - /// </summary> - /// <param name="infoCallback">Report string information to some channel</param> - public MamlModelMerger(Action<string> infoCallback) - { - _infoCallback = infoCallback; - } - - public MamlCommand Merge(MamlCommand metadataModel, MamlCommand stringModel, bool updateInputOutput) - { - MamlCommand result = null; - _cmdletUpdated = false; - - Report($"---- UPDATING Cmdlet : {metadataModel.Name} ----\r\n"); - try - { - result = new MamlCommand() - { - Name = metadataModel.Name, - Synopsis = stringModel.Synopsis, - Description = stringModel.Description, - Notes = stringModel.Notes, - Extent = stringModel.Extent - }; - } - catch (Exception ex) - { - Report($"---- ERROR UPDATING Cmdlet : {metadataModel.Name}----\r\n"); - Report($" Exception Creating Merged Object: \r\n{ex.Message}\r\n"); - _cmdletUpdated = true; - } - try - { - // TODO: convert into MergeMetadataProperty - result.Links.AddRange(stringModel.Links); - } - catch (Exception ex) - { - Report($"---- ERROR UPDATING Cmdlet : {metadataModel.Name}----\r\n"); - Report($" Exception Links: \r\n{ex.Message}\r\n"); - _cmdletUpdated = true; - } - try - { - // All examples come only from strtringModel - result.Examples.AddRange(stringModel.Examples); - } - catch (Exception ex) - { - Report($"---- ERROR UPDATING Cmdlet : {metadataModel.Name}----\r\n"); - Report($" Exception Examples: \r\n{ex.Message}\r\n"); - _cmdletUpdated = true; - } - - var model = updateInputOutput ? metadataModel : stringModel; - - try - { - // TODO: figure out what's the right thing for MamlInputOutput - result.Inputs.AddRange(model.Inputs); - result.Outputs.AddRange(model.Outputs); - } - catch (Exception ex) - { - Report($"---- ERROR UPDATING Cmdlet : {model.Name}----\r\n"); - Report($" Exception Inputs and Outputs: \r\n{ex.Message}\r\n"); - _cmdletUpdated = true; - } - - //Result takes in the merged parameter results. - MergeParameters(result, metadataModel, stringModel); - - if (!_cmdletUpdated) - { - Report("\tNo updates done\r\n"); - } - - Report($"---- COMPLETED UPDATING Cmdlet : {metadataModel.Name} ----\r\n\r\n"); - - return result; - } - - private MamlParameter FindParameterByName(string name, IEnumerable<MamlParameter> list) - { - return list.FirstOrDefault(x => StringComparer.OrdinalIgnoreCase.Equals(name, x.Name)); - } - - private void MergeParameters(MamlCommand result, MamlCommand metadataModel, MamlCommand stringModel) - { - try - { - // we care only about metadata for parameters in syntax - try - { - result.Syntax.AddRange(metadataModel.Syntax); - } - catch (Exception ex) - { - Report($"---- ERROR UPDATING Cmdlet : {metadataModel.Name}----\r\n"); - Report($" Exception adding parameter syntax to merge: \r\n{ex.Message}\r\n"); - _cmdletUpdated = true; - } - //reports changes to parameter set names - var metadataSyntaxSet = new SortedSet<MamlSyntax>(metadataModel.Syntax, new MamlSyntaxNameComparer()); - var stringSyntaxSet = new SortedSet<MamlSyntax>(stringModel.Syntax, new MamlSyntaxNameComparer()); - var removedSyntaxes = - stringSyntaxSet.Except(metadataSyntaxSet, new MamlParameterSetEqualityComparer()).ToList(); - var addedSyntaxes = - metadataSyntaxSet.Except(stringSyntaxSet, new MamlParameterSetEqualityComparer()).ToList(); - - foreach (var addedSyntax in addedSyntaxes) - { - Report($"\tParameter Set Added: {addedSyntax.ParameterSetName}\r\n"); - _cmdletUpdated = true; - } - foreach (var droppedSyntax in removedSyntaxes) - { - Report($"\tParameter Set Deleted: {droppedSyntax.ParameterSetName}\r\n"); - _cmdletUpdated = true; - } - - foreach (var metadataSyntax in metadataModel.Syntax) - { - var metadataParameters = new SortedSet<MamlParameter>(metadataSyntax.Parameters, - new MamlParameterNameComparer()); - - foreach (var stringSyntax in stringModel.Syntax) - { - var stringParameters = new SortedSet<MamlParameter>(stringSyntax.Parameters, - new MamlParameterNameComparer()); - if (metadataParameters.SetEquals(stringParameters) && - stringSyntax.ParameterSetName != metadataSyntax.ParameterSetName) - { - Report( - $"\tParameter Set Name Updated: {metadataSyntax.ParameterSetName}\r\n\t\tOld Set: {stringSyntax.ParameterSetName}\r\n\t\tNew Set: {metadataSyntax.ParameterSetName}\r\n"); - } - } - } - - //Processing Parameters for cmdlet - var stringParameterSet = new SortedSet<MamlParameter>(stringModel.Parameters, - new MamlParameterNameComparer()); - var metadataParameterSet = new SortedSet<MamlParameter>(metadataModel.Parameters, - new MamlParameterNameComparer()); - var addedParameters = - metadataParameterSet.Except(stringParameterSet, new MamlParameterEqualityComparer()).ToList(); - var removedParameters = - stringParameterSet.Except(metadataParameterSet, new MamlParameterEqualityComparer()).ToList(); - - foreach (var addedParam in addedParameters) - { - Report($"\tParameter Added: {addedParam.Name}\r\n"); - _cmdletUpdated = true; - } - foreach (var removedParam in removedParameters) - { - Report($"\tParameter Deleted: {removedParam.Name}\r\n"); - _cmdletUpdated = true; - } - - foreach (var param in metadataModel.Parameters) - { - var strParam = FindParameterByName(param.Name, stringModel.Parameters); - if (strParam != null) - { - try - { - param.Description = strParam.Description; - } - catch (Exception ex) - { - Report($"---- ERROR UPDATING Cmdlet : {metadataModel.Name}----\r\n"); - Report($" Exception {param.Name} description merge: \r\n{ex.Message}\r\n"); - _cmdletUpdated = true; - } - - try - { - param.DefaultValue = strParam.DefaultValue; - } - catch (Exception ex) - { - Report($"---- ERROR UPDATING Cmdlet : {metadataModel.Name}----\r\n"); - Report($" Exception {param.Name} default value merge: \r\n{ex.Message}\r\n"); - _cmdletUpdated = true; - } - // don't update type - // param.Type = strParam.Type; - try - { - param.Extent = strParam.Extent; - } - catch (Exception ex) - { - Report($"---- ERROR UPDATING Cmdlet : {metadataModel.Name}----\r\n"); - Report($" Exception {param.Name} extent merge: \r\n{ex.Message}\r\n"); - _cmdletUpdated = true; - } - - param.FormatOption = strParam.FormatOption; - } - - result.Parameters.Add(param); - } - - var matchedParametersSet = stringParameterSet.Intersect(metadataParameterSet,new MamlParameterEqualityComparer()).ToList(); - var matchedComparer = new MamlParameterAttributeComparer(); - - foreach (var matchedParam in matchedParametersSet) - { - var metadataMatch = metadataModel.Parameters.Single(p => p.Name == matchedParam.Name); - if (matchedComparer.Compare(matchedParam, metadataMatch) == 0) - { - continue; - } - if (matchedParam.Type != metadataMatch.Type) - { - _cmdletUpdated = true; - Report($"\tParameter Updated: {matchedParam.Name}\r\n\t\tType updated from {matchedParam.Type} to {metadataMatch.Type}\r\n"); - } - if (string.Join(",", matchedParam.Aliases) != string.Join(",", metadataMatch.Aliases)) - { - _cmdletUpdated = true; - Report($"\tParameter Updated: {matchedParam.Name}\r\n\t\tAliases updated from {string.Join(",",matchedParam.Aliases)} to {string.Join(",",metadataMatch.Aliases)}\r\n"); - } - if (matchedParam.Required != metadataMatch.Required) - { - _cmdletUpdated = true; - Report($"\tParameter Updated: {matchedParam.Name}\r\n\t\tRequired updated from {matchedParam.Required} to {metadataMatch.Required}\r\n"); - } - if (matchedParam.Position != metadataMatch.Position) - { - _cmdletUpdated = true; - Report($"\tParameter Updated: {matchedParam.Name}\r\n\t\tPosition updated from {matchedParam.Position} to {metadataMatch.Position}\r\n"); - } - if (matchedParam.DefaultValue != metadataMatch.DefaultValue) - { - _cmdletUpdated = true; - Report($"\tParameter Updated: {matchedParam.Name}\r\n\t\tDefault Value updated from {matchedParam.DefaultValue} to {metadataMatch.DefaultValue}\r\n"); - } - if (matchedParam.PipelineInput != metadataMatch.PipelineInput) - { - _cmdletUpdated = true; - Report($"\tParameter Updated: {matchedParam.Name}\r\n\t\tAccepts Pipeline Input updated from {matchedParam.PipelineInput} to {metadataMatch.PipelineInput}\r\n"); - } - if (matchedParam.Globbing != metadataMatch.Globbing) - { - _cmdletUpdated = true; - Report($"\tParameter Updated: {matchedParam.Name}\r\n\t\tAccepts wildcard characters updated from {matchedParam.Globbing} to {metadataMatch.Globbing}\r\n"); - } - } - } - catch (Exception ex) - { - Report($"---- ERROR UPDATING Cmdlet : {metadataModel.Name}----\r\n"); - Report($" Exception parameter merge: \r\n{ex.Message}\r\n"); - _cmdletUpdated = true; - } - } - - private void Report(string format, params object[] objects) - { - if (_infoCallback != null) - { - _infoCallback.Invoke(string.Format(format, objects)); - } - } - } - - -} diff --git a/v1/src/Markdown.MAML/Transformer/MamlMultiModelMerger.cs b/v1/src/Markdown.MAML/Transformer/MamlMultiModelMerger.cs deleted file mode 100644 index a0d84dac..00000000 --- a/v1/src/Markdown.MAML/Transformer/MamlMultiModelMerger.cs +++ /dev/null @@ -1,331 +0,0 @@ -using Markdown.MAML.Model.MAML; -using Markdown.MAML.Model.Markdown; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Markdown.MAML.Transformer -{ - /// <summary> - /// Model merger that's capable of combining few models at once. - /// It's useful for scenarios, when you want to assign applicable tags to parameters. - /// </summary> - public class MamlMultiModelMerger - { - private Action<string> _infoCallback; - private bool _ignoreTagsIfAllApplicable; - private string _mergeMarker; - - public MamlMultiModelMerger() : this(null, true, "!!! ") { } - - /// <summary> - /// </summary> - /// <param name="infoCallback">Report string information to some channel</param> - /// <param name="ignoreTagsIfAllApplicable">if True merger will skip adding applicable tags if it's applicable to all</param> - public MamlMultiModelMerger(Action<string> infoCallback, bool ignoreTagsIfAllApplicable, string mergeMarker) - { - _infoCallback = infoCallback; - _ignoreTagsIfAllApplicable = ignoreTagsIfAllApplicable; - _mergeMarker = mergeMarker; - } - - public MamlCommand Merge(Dictionary<string, MamlCommand> applicableTag2Model) - { - if (applicableTag2Model.Count == 0) - { - throw new ArgumentException("applicableTag2Model"); - } - - var tagsModel = applicableTag2Model.ToList(); - - // just take one model to use name from it and such - var referenceModel = applicableTag2Model.First().Value; - - MamlCommand result = null; - result = new MamlCommand() - { - Name = referenceModel.Name, - Synopsis = new SectionBody(MergeText(tagsModel.ToDictionary(pair => pair.Key, pair => pair.Value.Synopsis?.Text))), - Description = new SectionBody(MergeText(tagsModel.ToDictionary(pair => pair.Key, pair => pair.Value.Description?.Text))), - Notes = new SectionBody(MergeText(tagsModel.ToDictionary(pair => pair.Key, pair => pair.Value.Notes?.Text))), - Extent = referenceModel.Extent - }; - - result.Links.AddRange(MergeSimplifiedLinks(tagsModel.Select(pair => pair.Value.Links))); - - MergeExamples(result, applicableTag2Model); - - result.Inputs.AddRange(MergeEntityList(tagsModel.Select(pair => pair.Value.Inputs))); - result.Outputs.AddRange(MergeEntityList(tagsModel.Select(pair => pair.Value.Outputs))); - - MergeParameters(result, applicableTag2Model); - return result; - } - - private IEnumerable<MamlLink> MergeSimplifiedLinks(IEnumerable<List<MamlLink>> linksList) - { - // In theory we could simply use MergeEntityList, but we have this SimplifiedLinks hack: - // we just put whole paragraphs of text into LinkName. - - // To acoount for it we should - // split any simplified link into separate ones. - // Then we can combine them and return in the form of simplified links. - - List<List<MamlLink>> candidates = new List<List<MamlLink>>(); - foreach (var links in linksList) - { - foreach (var link in links) - { - if (!link.IsSimplifiedTextLink) - { - throw new ArgumentException("All links are expected in simplified form"); - } - string[] segments = link.LinkName.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); - candidates.Add(segments.Select(s => new MamlLink(isSimplifiedTextLink: true) { LinkName = s.Trim() + "\r\n\r\n" }).ToList()); - } - } - - return MergeEntityList(candidates); - } - - /// <summary> - /// Merge entities, exclude duplicates and preserve the order. - /// </summary> - /// <param name="links"></param> - /// <returns></returns> - private List<TEntity> MergeEntityList<TEntity>(IEnumerable<List<TEntity>> entities) - where TEntity : IEquatable<TEntity> - { - List<TEntity> result = new List<TEntity>(); - foreach(var entity in entities) - { - foreach (var candidate in entity) - { - // this cycle can be optimized but that's fine - bool found = false; - foreach (var added in result) - { - if (added.Equals(candidate)) - { - found = true; - break; - } - } - - if (!found) - { - result.Add(candidate); - } - } - } - - return result; - } - - /// <summary> - /// Merge Parameter lists, exclude duplicates by name and preserve the order. - /// </summary> - /// <param name="links"></param> - /// <returns></returns> - private List<MamlParameter> MergeParameterList(IEnumerable<List<MamlParameter>> parameterLists) - { - List<MamlParameter> result = new List<MamlParameter>(); - foreach (var list in parameterLists) - { - foreach (var candidate in list) - { - // this cycle can be optimized but that's fine - bool found = false; - foreach (var added in result) - { - if (StringComparer.OrdinalIgnoreCase.Equals(added.Name, candidate.Name)) - { - found = true; - break; - } - } - - if (!found) - { - result.Add(candidate); - } - } - } - - return result; - } - - /// <summary> - /// Combine examples together. - /// If examples are identical, we deduplicate them. - /// If example is not found in all the models, add the applicable tags in parentheses. - /// </summary> - /// <param name="result"></param> - /// <param name="applicableTag2Model"></param> - private void MergeExamples(MamlCommand result, Dictionary<string, MamlCommand> applicableTag2Model) - { - // We want to more or less keep the order of the original examples. - // To do it, we use the following algorithm: - // We are adding examples sequentially: - // 1st from every model, 2nd from every model, etc. - // At the same time we are doing deduplication by hashcode. - - // this dictonary gives the mapping between example hashes and applicable tags - var hash2tag = new Dictionary<int, List<String>>(); - foreach (var pair in applicableTag2Model) - { - foreach (var example in pair.Value.Examples) { - List<String> tagList; - int hash = example.GetHashCode(); - if (!hash2tag.TryGetValue(hash, out tagList)) - { - tagList = new List<string>(); - hash2tag[hash] = tagList; - } - tagList.Add(pair.Key); - } - } - - // this hashset contains the example hashes for already used examples - var usedHashes = new HashSet<int>(); - - int max = applicableTag2Model.Select(pair => pair.Value.Examples.Count).Max(); - for (int i = 0; i < max; i++) - { - foreach (var pair in applicableTag2Model) - { - if (pair.Value.Examples.Count > i) - { - var example = pair.Value.Examples.ElementAt(i); - int hash = example.GetHashCode(); - if (usedHashes.Contains(hash)) { - continue; - } - // if all tags are covered, don't add anything - if (hash2tag[hash].Count < applicableTag2Model.Count) - { - // we will sort the same list few times, but that's fine - hash2tag[hash].Sort(); - string listString = string.Join(", ", hash2tag[hash]); - example.Title += string.Format(" ({0})", listString); - } - usedHashes.Add(hash); - result.Examples.Add(example); - } - } - } - } - - private MamlParameter FindParameterByName(string name, IEnumerable<MamlParameter> list) - { - return list.FirstOrDefault(x => StringComparer.OrdinalIgnoreCase.Equals(name, x.Name)); - } - - private void MergeParameters(MamlCommand result, Dictionary<string, MamlCommand> applicableTag2Model) - { - // First handle syntax. - // To avoid dealing with complicated applicableTag + ParameterSetName pairs. - // They already serve very similar purpose. - // - // We simply merge syntaxes of the same name. That way all possible parameter names from all applicable tags - // apearing in the syntax. This is not ideal, but alternative would be introducing "applicable" for syntax. - // That would make it even more complicated. - var tagsModel = applicableTag2Model.ToList(); - var syntaxes = tagsModel.SelectMany(pair => pair.Value.Syntax); - var syntaxNames = syntaxes.Select(syntax => syntax.ParameterSetName).Distinct(StringComparer.OrdinalIgnoreCase); - var defaultSyntaxNames = syntaxes.Where(syntax => syntax.IsDefault).Select(syntax => syntax.ParameterSetName).Distinct(StringComparer.OrdinalIgnoreCase); - if (defaultSyntaxNames.Count() > 1) - { - // reporting warning and continue - Report("Found conflicting default ParameterSets ({0}) in applicableTags ({1})", - string.Join(", ", defaultSyntaxNames), string.Join(", ", applicableTag2Model.Keys)); - } - string defaultSyntaxName = defaultSyntaxNames.FirstOrDefault(); - - foreach (string syntaxName in syntaxNames) - { - var newSyntax = new MamlSyntax() - { - ParameterSetName = syntaxName, - IsDefault = StringComparer.OrdinalIgnoreCase.Equals(defaultSyntaxName, syntaxName), - }; - - var paramSetsToMerge = syntaxes.Where(syntax => StringComparer.OrdinalIgnoreCase.Equals(syntax.ParameterSetName, syntaxName)); - - newSyntax.Parameters.AddRange(MergeParameterList(paramSetsToMerge.Select(syntax => syntax.Parameters))); - result.Syntax.Add(newSyntax); - } - - // Then merge individual parameters - - var allNames = tagsModel.SelectMany(pair => pair.Value.Parameters).Select(p => p.Name).Distinct().ToList(); - foreach (string name in allNames) - { - Dictionary<string, MamlParameter> paramsToMerge = new Dictionary<string, MamlParameter>(); - foreach (var pair in tagsModel) - { - MamlParameter candidate = FindParameterByName(name, pair.Value.Parameters); - if (candidate != null) - { - paramsToMerge[pair.Key] = candidate; - } - } - - string newDescription = MergeText(paramsToMerge.ToDictionary(pair => pair.Key, pair => pair.Value.Description)); - var newParameter = paramsToMerge.First().Value.Clone(); - newParameter.Description = newDescription; - if (paramsToMerge.Count != applicableTag2Model.Count || !this._ignoreTagsIfAllApplicable) - { - // we should not update applicable tags, if it's applicable to everything and not explicitly specified - newParameter.Applicable = paramsToMerge.Select(p => p.Key).ToArray(); - } - - result.Parameters.Add(newParameter); - } - } - - /// <summary> - /// Merges text attributed with tags into a single representation - /// </summary> - private string MergeText(Dictionary<string, string> applicableTag2Text) - { - var reverseMap = new Dictionary<string, List<string>>(); - foreach (var pair in applicableTag2Text) - { - string pretty = pair.Value != null ? pair.Value : ""; - List<string> tags; - if (!reverseMap.TryGetValue(pretty, out tags)) - { - tags = new List<string>(); - reverseMap[pretty] = tags; - } - tags.Add(pair.Key); - } - - if (reverseMap.Count == 1) - { - return reverseMap.Keys.First(); - } - - var result = new StringBuilder(); - foreach (var pair in reverseMap) - { - var tagsString = string.Join(", ", pair.Value); - result.AppendFormat("{0}{1}{2}{2}{3}{2}{2}", _mergeMarker, tagsString, "\r\n", pair.Key); - } - - return result.ToString(); - } - - private void Report(string format, params object[] objects) - { - if (_infoCallback != null) - { - _infoCallback.Invoke(string.Format(format, objects)); - } - } - } - - -} diff --git a/v1/src/Markdown.MAML/Transformer/ModelTransformerBase.cs b/v1/src/Markdown.MAML/Transformer/ModelTransformerBase.cs deleted file mode 100644 index 1e07e694..00000000 --- a/v1/src/Markdown.MAML/Transformer/ModelTransformerBase.cs +++ /dev/null @@ -1,498 +0,0 @@ -using Markdown.MAML.Model.MAML; -using Markdown.MAML.Model.Markdown; -using Markdown.MAML.Parser; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Markdown.MAML.Transformer -{ - public abstract class ModelTransformerBase : IModelTransformer - { - private DocumentNode _root; - private IEnumerator<MarkdownNode> _rootEnumerator; - private Action<string> _infoCallback; - private Action<string> _warningCallback; - - internal const int COMMAND_NAME_HEADING_LEVEL = 1; - internal const int COMMAND_ENTRIES_HEADING_LEVEL = 2; - internal const int PARAMETER_NAME_HEADING_LEVEL = 3; - internal const int INPUT_OUTPUT_TYPENAME_HEADING_LEVEL = 3; - internal const int EXAMPLE_HEADING_LEVEL = 3; - internal const int PARAMETERSET_NAME_HEADING_LEVEL = 3; - - public ModelTransformerBase(Action<string> infoCallback, Action<string> warningCallback) - { - _infoCallback = infoCallback; - _warningCallback = warningCallback; - } - - public IEnumerable<MamlCommand> NodeModelToMamlModel(DocumentNode node) - { - _root = node; - if (_root.Children == null) - { - // HACK: - _rootEnumerator = (new LinkedList<MarkdownNode>()).GetEnumerator(); - } - else - { - _rootEnumerator = _root.Children.GetEnumerator(); - } - - List<MamlCommand> commands = new List<MamlCommand>(); - MarkdownNode markdownNode; - while ((markdownNode = GetNextNode()) != null) - { - if (markdownNode is HeadingNode) - { - var headingNode = markdownNode as HeadingNode; - switch (headingNode.HeadingLevel) - { - case COMMAND_NAME_HEADING_LEVEL: - { - MamlCommand command = new MamlCommand() - { - Name = headingNode.Text, - Extent = headingNode.SourceExtent, - // we have explicit entry for common parameters in markdown - SupportCommonParameters = false - }; - - if (_infoCallback != null) - { - _infoCallback.Invoke("Start processing command " + command.Name); - } - - // fill up command - while (SectionDispatch(command)) { } - - commands.Add(command); - break; - } - default: throw new HelpSchemaException(headingNode.SourceExtent, "Booo, I don't know what is the heading level " + headingNode.HeadingLevel); - } - } - } - return commands; - } - - private MarkdownNode _ungotNode { get; set; } - - protected MarkdownNode GetCurrentNode() - { - if (_ungotNode != null) - { - var node = _ungotNode; - return node; - } - - return _rootEnumerator.Current; - } - - protected MarkdownNode GetNextNode() - { - if (_ungotNode != null) - { - _ungotNode = null; - return _rootEnumerator.Current; - } - - if (_rootEnumerator.MoveNext()) - { - return _rootEnumerator.Current; - } - - return null; - } - - protected void UngetNode(MarkdownNode node) - { - if (_ungotNode != null) - { - throw new ArgumentException("Cannot ungot token, already ungot one"); - } - - _ungotNode = node; - } - - protected string SimpleTextSectionRule() - { - // grammar: - // Simple paragraph Text - return GetTextFromParagraphNode(ParagraphNodeRule()); - } - - protected void InputsRule(MamlCommand commmand) - { - MamlInputOutput input; - while ((input = InputOutputRule()) != null) - { - commmand.Inputs.Add(input); - } - } - - protected void OutputsRule(MamlCommand commmand) - { - MamlInputOutput output; - while ((output = InputOutputRule()) != null) - { - commmand.Outputs.Add(output); - } - } - - protected void ExamplesRule(MamlCommand commmand) - { - MamlExample example; - while ((example = ExampleRule()) != null) - { - commmand.Examples.Add(example); - } - } - - protected MamlExample ExampleRule() - { - // grammar: - // #### ExampleTitle - // Introduction - // ``` - // code - // ``` - // Remarks - var node = GetNextNode(); - try - { - var headingNode = GetHeadingWithExpectedLevel(node, EXAMPLE_HEADING_LEVEL); - - if (headingNode == null) - { - return null; - } - - MamlExample example = new MamlExample() - { - Title = headingNode.Text - }; - example.Introduction = GetTextFromParagraphNode(ParagraphNodeRule()); - example.FormatOption = headingNode.FormatOption; - CodeBlockNode codeBlockNode; - List<MamlCodeBlock> codeBlocks = new List<MamlCodeBlock>(); - - while ((codeBlockNode = CodeBlockRule()) != null) - { - codeBlocks.Add(new MamlCodeBlock( - codeBlockNode.Text, - codeBlockNode.LanguageMoniker - )); - } - - example.Code = codeBlocks.ToArray(); - - example.Remarks = GetTextFromParagraphNode(ParagraphNodeRule()); - - return example; - } - catch (HelpSchemaException headingException) - { - Report("Schema exception. This can occur when there are multiple code blocks in one example. " + headingException.Message); - - throw headingException; - } - - } - - protected void RelatedLinksRule(MamlCommand commmand) - { - var paragraphNode = ParagraphNodeRule(); - if (paragraphNode == null) - { - return; - } - - foreach (var paragraphSpan in paragraphNode.Spans) - { - if (paragraphSpan.ParserMode == ParserMode.FormattingPreserve) - { - commmand.Links.Add(new MamlLink(isSimplifiedTextLink: true) - { - LinkName = paragraphSpan.Text, - }); - } - else - { - var linkSpan = paragraphSpan as HyperlinkSpan; - if (linkSpan != null) - { - commmand.Links.Add(new MamlLink() - { - LinkName = linkSpan.Text, - LinkUri = linkSpan.Uri - }); - } - else - { - throw new HelpSchemaException(paragraphSpan.SourceExtent, "Expect hyperlink, but got " + paragraphSpan.Text); - } - } - } - } - - protected MamlInputOutput InputOutputRule() - { - // grammar: - // #### TypeName - // Description - var node = GetNextNode(); - var headingNode = GetHeadingWithExpectedLevel(node, INPUT_OUTPUT_TYPENAME_HEADING_LEVEL); - if (headingNode == null) - { - return null; - } - - MamlInputOutput typeEntity = new MamlInputOutput() - { - TypeName = headingNode.Text, - Description = SimpleTextSectionRule(), - FormatOption = headingNode.FormatOption - }; - - return typeEntity; - } - - protected SourceExtent GetExtent(MarkdownNode node) - { - TextNode textNode = node as TextNode; - if (textNode != null) - { - return textNode.SourceExtent; - } - ParagraphNode paragraphNode = node as ParagraphNode; - if (paragraphNode != null && paragraphNode.Spans.Any()) - { - return paragraphNode.Spans.First().SourceExtent; - } - - return new SourceExtent("", 0, 0, 0, 0, null); - } - - /// <summary> - /// - /// </summary> - /// <param name="node"></param> - /// <param name="level"></param> - /// <returns> - /// return headingNode if expected heading level encounterd. - /// null, if higher level encountered. - /// throw exception, if unexpected node encountered. - /// </returns> - protected HeadingNode GetHeadingWithExpectedLevel(MarkdownNode node, int level) - { - if (node == null) - { - return null; - } - - // check for appropriate header - if (node.NodeType != MarkdownNodeType.Heading) - { - throw new HelpSchemaException(GetExtent(node), "Expect Heading"); - } - - var headingNode = node as HeadingNode; - if (headingNode.HeadingLevel < level) - { - UngetNode(node); - return null; - } - - if (headingNode.HeadingLevel != level) - { - throw new HelpSchemaException(headingNode.SourceExtent, "Expect Heading level " + level); - } - return headingNode; - } - - /// <summary> - /// </summary> - /// <returns> - /// return paragraphNode if encounterd. - /// null, if any header level encountered. - /// throw exception, if other unexpected node encountered. - /// </returns> - protected ParagraphNode ParagraphNodeRule() - { - var node = GetNextNode(); - if (node == null) - { - return null; - } - - switch (node.NodeType) - { - case MarkdownNodeType.Paragraph: - break; - case MarkdownNodeType.CodeBlock: - case MarkdownNodeType.Heading: - UngetNode(node); - return null; - default: - throw new HelpSchemaException(GetExtent(node), "Expect Paragraph"); - } - - return node as ParagraphNode; - } - - protected string ParagraphOrCodeBlockNodeRule(string excludeLanguageMoniker) - { - var res = new List<string>(); - MarkdownNode node; - - while ((node = GetNextNode()) != null) - { - bool breakFlag = false; - switch (node.NodeType) - { - case MarkdownNodeType.Paragraph: - { - res.Add(GetTextFromParagraphNode(node as ParagraphNode)); - break; - } - case MarkdownNodeType.CodeBlock: - { - var codeblock = node as CodeBlockNode; - if (!String.Equals(excludeLanguageMoniker, codeblock.LanguageMoniker, StringComparison.OrdinalIgnoreCase)) - { - res.Add(codeblock.Text); - } - else - { - UngetNode(node); - breakFlag = true; - } - - break; - } - case MarkdownNodeType.Heading: - { - UngetNode(node); - breakFlag = true; - break; - } - default: - { - throw new HelpSchemaException(GetExtent(node), "Expect Paragraph or CodeBlock"); - } - } - - if (breakFlag) - { - break; - } - } - - return string.Join("\r\n\r\n", res); - } - - /// <summary> - /// </summary> - /// <returns> - /// return paragraphNode if encounterd. - /// null, if any header level encountered. - /// throw exception, if other unexpected node encountered. - /// </returns> - protected CodeBlockNode CodeBlockRule() - { - var node = GetNextNode(); - if (node == null) - { - return null; - } - - switch (node.NodeType) - { - case MarkdownNodeType.CodeBlock: - break; - case MarkdownNodeType.Heading: - case MarkdownNodeType.Paragraph: - UngetNode(node); - return null; - default: - throw new HelpSchemaException(GetExtent(node), "Expect CodeBlock"); - } - - return node as CodeBlockNode; - } - - private string GetTextFromParagraphSpans(IEnumerable<ParagraphSpan> spans) - { - // in preserve formatting there is only one span all the time - if (spans.Count() == 1) - { - var textSpan = spans.First() as TextSpan; - if (textSpan.ParserMode == ParserMode.FormattingPreserve) - { - return textSpan.Text; - } - } - - StringBuilder sb = new StringBuilder(); - bool first = true; - bool previousSpanIsSpecial = false; - foreach (var paragraphSpan in spans) - { - // TODO: make it handle hyperlinks, codesnippets, italic, bold etc more wisely - HyperlinkSpan hyperlink = paragraphSpan as HyperlinkSpan; - TextSpan text = paragraphSpan as TextSpan; - bool spanIsSpecial = hyperlink != null || (text != null && text.Style != TextSpanStyle.Normal); - if (!first && spanIsSpecial) - { - sb.Append(" "); - } - else if (previousSpanIsSpecial) - { - sb.Append(" "); - } - - sb.Append(paragraphSpan.Text); - previousSpanIsSpecial = spanIsSpecial; - if (hyperlink != null) - { - if (!string.IsNullOrWhiteSpace(hyperlink.Uri)) - { - sb.AppendFormat(" ({0})", hyperlink.Uri); - previousSpanIsSpecial = false; - } - } - - first = false; - - } - return sb.ToString(); - } - - protected string GetTextFromParagraphNode(ParagraphNode node) - { - if (node == null) - { - return ""; - } - return GetTextFromParagraphSpans(node.Spans); - } - - /// <summary> - /// - /// </summary> - /// <param name="command"></param> - /// <returns>true if Section was found</returns> - protected abstract bool SectionDispatch(MamlCommand command); - - protected void Report(string warning) - { - if (_warningCallback != null) - { - _warningCallback.Invoke("Error encountered: " + warning); - } - } - } -} diff --git a/v1/src/Markdown.MAML/Transformer/ModelTransformerVersion2.cs b/v1/src/Markdown.MAML/Transformer/ModelTransformerVersion2.cs deleted file mode 100644 index 52954bcb..00000000 --- a/v1/src/Markdown.MAML/Transformer/ModelTransformerVersion2.cs +++ /dev/null @@ -1,469 +0,0 @@ -using Markdown.MAML.Model.MAML; -using Markdown.MAML.Model.Markdown; -using Markdown.MAML.Resources; -using System; -using System.Collections.Generic; -using System.Linq; -using Markdown.MAML.Parser; - -namespace Markdown.MAML.Transformer -{ - public class ModelTransformerVersion2 : ModelTransformerBase - { - List<Tuple<string, Dictionary<string, MamlParameter>>> _parameterName2ParameterSetMap = - new List<Tuple<string, Dictionary<string, MamlParameter>>>(); - - public static readonly string ALL_PARAM_SETS_MONIKER = "(All)"; - private String[] _applicableTag; - public ModelTransformerVersion2() : this(null, null, null) { } - - /// <summary> - /// </summary> - /// <param name="infoCallback">Report string information to some callback</param> - /// <param name="warningCallback">Report string warnings to some callback</param> - /// <param name="applicableTag">tag to filter out applicable Parameters, null accept everything</param> - public ModelTransformerVersion2(Action<string> infoCallback, Action<string> warningCallback, String[] applicableTag) : base(infoCallback, warningCallback) - { - _applicableTag = applicableTag; - } - - /// <summary> - /// - /// </summary> - /// <param name="command"></param> - /// <returns>true if Section was found</returns> - override protected bool SectionDispatch(MamlCommand command) - { - var node = GetNextNode(); - var headingNode = GetHeadingWithExpectedLevel(node, COMMAND_ENTRIES_HEADING_LEVEL); - if (headingNode == null) - { - return false; - } - - // TODO: When we are going to implement Localization story, we would need to replace - // this strings by MarkdownStrings values. - switch (headingNode.Text.ToUpper()) - { - case "DESCRIPTION": - { - command.Description = new SectionBody(SimpleTextSectionRule(), headingNode.FormatOption); - break; - } - case "SYNOPSIS": - { - command.Synopsis = new SectionBody(SimpleTextSectionRule(), headingNode.FormatOption); - break; - } - case "SYNTAX": - { - SyntaxRule(command); - break; - } - case "EXAMPLES": - { - ExamplesRule(command); - break; - } - case "PARAMETERS": - { - ParametersRule(command); - break; - } - case "INPUTS": - { - InputsRule(command); - break; - } - case "OUTPUTS": - { - OutputsRule(command); - break; - } - case "NOTES": - { - command.Notes = new SectionBody(SimpleTextSectionRule(), headingNode.FormatOption); - break; - } - case "RELATED LINKS": - { - RelatedLinksRule(command); - break; - } - default: - { - throw new HelpSchemaException(headingNode.SourceExtent, "Unexpected header name " + headingNode.Text); - } - } - return true; - } - - protected void SyntaxRule(MamlCommand commmand) - { - MamlSyntax syntax; - while ((syntax = SyntaxEntryRule()) != null) - { - //this is the only way to retain information on which syntax is the default - // without adding new members to command object. - //Though the cmdlet object, does have a member which contains the default syntax name only. - if (syntax.IsDefault) { commmand.Syntax.Add(syntax); } - } - } - - protected MamlSyntax SyntaxEntryRule() - { - // grammar: - // ### ParameterSetName - // ``` - // code - // ``` - - MamlSyntax syntax; - - var node = GetNextNode(); - if (node.NodeType == MarkdownNodeType.CodeBlock) - { - // if header is omitted - syntax = new MamlSyntax() - { - ParameterSetName = ALL_PARAM_SETS_MONIKER, - IsDefault = true - }; - } - else - { - var headingNode = GetHeadingWithExpectedLevel(node, PARAMETERSET_NAME_HEADING_LEVEL); - if (headingNode == null) - { - return null; - } - - bool isDefault = headingNode.Text.EndsWith(MarkdownStrings.DefaultParameterSetModifier); - syntax = new MamlSyntax() - { - ParameterSetName = isDefault ? headingNode.Text.Substring(0, headingNode.Text.Length - MarkdownStrings.DefaultParameterSetModifier.Length) : headingNode.Text, - IsDefault = isDefault - }; - - var codeBlock = CodeBlockRule(); - } - // we don't use the output of it - // TODO: we should capture syntax and verify that it's complient. - return syntax; - } - - protected void ParametersRule(MamlCommand command) - { - while (ParameterRule(command)) - { - } - - GatherSyntax(command); - } - - private void FillUpSyntax(MamlSyntax syntax, string name) - { - var parametersList = new List<MamlParameter>(); - - foreach (var pair in _parameterName2ParameterSetMap) - { - MamlParameter param = null; - if (pair.Item2.ContainsKey(name)) - { - param = pair.Item2[name]; - } - else - { - if (pair.Item2.Count == 1 && pair.Item2.First().Key == ALL_PARAM_SETS_MONIKER) - { - param = pair.Item2.First().Value; - } - } - if (param != null) - { - parametersList.Add(param); - } - } - - // order parameters based on position - // User OrderBy instead of Sort for stable sort - syntax.Parameters.AddRange(parametersList.OrderBy(x => x.Position)); - } - - private void GatherSyntax(MamlCommand command) - { - var parameterSetNames = GetParameterSetNames(); - var defaultSetName = string.Empty; - - if(command.Syntax.Count == 1 && command.Syntax[0].IsDefault) - { - //checks for existing IsDefault paramset and remove it while saving the name - defaultSetName = command.Syntax[0].ParameterSetName; - command.Syntax.Remove(command.Syntax[0]); - } - - if (parameterSetNames.Count == 0) - { - // special case: there are no parameters and hence there is only one parameter set - MamlSyntax syntax = new MamlSyntax(); - command.Syntax.Add(syntax); - } - - foreach (var setName in parameterSetNames) - { - MamlSyntax syntax = new MamlSyntax(); - if (setName == ALL_PARAM_SETS_MONIKER) - { - if (parameterSetNames.Count == 1) - { - // special case: there is only one parameter set and it's the default one - // we don't specify the name in this case. - } - else - { - continue; - } - } - else - { - syntax.ParameterSetName = StringComparer.OrdinalIgnoreCase.Equals(syntax.ParameterSetName, defaultSetName) - ? string.Format("{0}{1}", setName, MarkdownStrings.DefaultParameterSetModifier) - : setName; - } - - FillUpSyntax(syntax, setName); - command.Syntax.Add(syntax); - } - } - - private List<string> GetParameterSetNames() - { - // Inefficient alogrithm, but it's fine, because all collections are pretty small. - var parameterSetNames = new List<string>(); - foreach (var pair in _parameterName2ParameterSetMap) - { - foreach (var pair2 in pair.Item2) - { - var paramSetName = pair2.Key; - - bool found = false; - foreach (var candidate in parameterSetNames) - { - if (StringComparer.OrdinalIgnoreCase.Equals(candidate, paramSetName)) - { - found = true; - break; - } - } - - if (!found) - { - parameterSetNames.Add(paramSetName); - } - } - } - - return parameterSetNames; - } - - private bool IsKnownKey(string key) - { - return StringComparer.OrdinalIgnoreCase.Equals(key, MarkdownStrings.Type) || - StringComparer.OrdinalIgnoreCase.Equals(key, MarkdownStrings.Parameter_Sets) || - StringComparer.OrdinalIgnoreCase.Equals(key, MarkdownStrings.Aliases) || - StringComparer.OrdinalIgnoreCase.Equals(key, MarkdownStrings.Accepted_values) || - StringComparer.OrdinalIgnoreCase.Equals(key, MarkdownStrings.Required) || - StringComparer.OrdinalIgnoreCase.Equals(key, MarkdownStrings.Position) || - StringComparer.OrdinalIgnoreCase.Equals(key, MarkdownStrings.Default_value) || - StringComparer.OrdinalIgnoreCase.Equals(key, MarkdownStrings.Accept_pipeline_input) || - StringComparer.OrdinalIgnoreCase.Equals(key, MarkdownStrings.Accept_wildcard_characters) || - StringComparer.OrdinalIgnoreCase.Equals(key, MarkdownStrings.Applicable); - } - - /// <summary> - /// we only parse simple key-value pairs here - /// </summary> - /// <param name="yamlSnippet"></param> - /// <returns></returns> - private Dictionary<string, string> ParseYamlKeyValuePairs(CodeBlockNode yamlSnippet) - { - Dictionary<string, string> result; - try - { - result = MarkdownParser.ParseYamlKeyValuePairs(yamlSnippet.Text); - } - catch (ArgumentException) - { - throw new HelpSchemaException(yamlSnippet.SourceExtent, "Invalid yaml: expected simple key-value pairs"); - } - - foreach (var pair in result) - { - if (!IsKnownKey(pair.Key)) - { - throw new HelpSchemaException(yamlSnippet.SourceExtent, "Invalid yaml: unknown key " + pair.Key); - } - } - - return result; - } - - private string[] SplitByCommaAndTrim(string input) - { - if (input == null) - { - return new string[0]; - } - - return input.Split(',').Select(x => x.Trim()).ToArray(); - } - - private void FillUpParameterFromKeyValuePairs(Dictionary<string, string> pairs, MamlParameter parameter) - { - // for all null keys, we should ignore the value in this context - var newPairs = new Dictionary<string, string>(pairs.Comparer); - - foreach (var pair in pairs) - { - if (pair.Value != null) - { - newPairs[pair.Key] = pair.Value; - } - } - - pairs = newPairs; - - string value; - parameter.Type = pairs.TryGetValue(MarkdownStrings.Type, out value) ? value : null; - parameter.Aliases = pairs.TryGetValue(MarkdownStrings.Aliases, out value) ? SplitByCommaAndTrim(value) : new string [0]; - parameter.ParameterValueGroup.AddRange(pairs.TryGetValue(MarkdownStrings.Accepted_values, out value) ? SplitByCommaAndTrim(value) : new string[0]); - parameter.Required = pairs.TryGetValue(MarkdownStrings.Required, out value) ? StringComparer.OrdinalIgnoreCase.Equals("true", value) : false; - parameter.Position = pairs.TryGetValue(MarkdownStrings.Position, out value) ? value : "named"; - parameter.DefaultValue = pairs.TryGetValue(MarkdownStrings.Default_value, out value) ? value : null; - parameter.PipelineInput = pairs.TryGetValue(MarkdownStrings.Accept_pipeline_input, out value) ? value : "false"; - parameter.Globbing = pairs.TryGetValue(MarkdownStrings.Accept_wildcard_characters, out value) ? StringComparer.OrdinalIgnoreCase.Equals("true", value) : false; - // having Applicable for the whole parameter is a little bit sloppy: ideally it should be per yaml entry. - // but that will make the code super ugly and it's unlikely that these two features would need to be used together. - parameter.Applicable = pairs.TryGetValue(MarkdownStrings.Applicable, out value) ? SplitByCommaAndTrim(value) : null; - } - - private bool ParameterRule(MamlCommand commmand) - { - // grammar: - // #### -Name - // Description - optional, there also could be codesnippets in the description - // but no yaml codesnippets - // - // ```yaml - one entry for every unique parameter metadata set - // ... - // ``` - - var node = GetNextNode(); - var headingNode = GetHeadingWithExpectedLevel(node, PARAMETER_NAME_HEADING_LEVEL); - if (headingNode == null) - { - return false; - } - - var name = headingNode.Text; - if (name.Length > 0 && name[0] == '-') - { - name = name.Substring(1); - } - - MamlParameter parameter = new MamlParameter() - { - Name = name, - Extent = headingNode.SourceExtent - }; - - parameter.Description = ParagraphOrCodeBlockNodeRule("yaml"); - parameter.FormatOption = headingNode.FormatOption; - - if (StringComparer.OrdinalIgnoreCase.Equals(parameter.Name, MarkdownStrings.CommonParametersToken)) - { - // ignore text body - commmand.SupportCommonParameters = true; - return true; - } - - if (StringComparer.OrdinalIgnoreCase.Equals(parameter.Name, MarkdownStrings.WorkflowParametersToken)) - { - // ignore text body - commmand.IsWorkflow = true; - return true; - } - - // we are filling up two pieces here: Syntax and Parameters - // we are adding this parameter object to the parameters and later modifying it - // in the rare case, when there are multiply yaml snippets, - // the first one should be present in the resulted maml in the Parameters section - // (all of them would be present in Syntax entry) - var parameterSetMap = new Dictionary<string, MamlParameter>(StringComparer.OrdinalIgnoreCase); - - CodeBlockNode codeBlock; - - // fill up couple other things, even if there are no codeBlocks - // if there are, we will fill it up inside - parameter.ValueRequired = true; - - // First parameter is what should be used in the Parameters section - MamlParameter firstParameter = null; - bool isAtLeastOneYaml = false; - - while ((codeBlock = CodeBlockRule()) != null) - { - isAtLeastOneYaml = true; - var yaml = ParseYamlKeyValuePairs(codeBlock); - FillUpParameterFromKeyValuePairs(yaml, parameter); - - parameter.ValueRequired = parameter.IsSwitchParameter() ? false : true; - - // handle applicable tag - if (parameter.IsApplicable(this._applicableTag)) - { - if (firstParameter == null) - { - firstParameter = parameter; - } - - // handle parameter sets - if (yaml.ContainsKey(MarkdownStrings.Parameter_Sets)) - { - foreach (string parameterSetName in SplitByCommaAndTrim(yaml[MarkdownStrings.Parameter_Sets])) - { - if (string.IsNullOrEmpty(parameterSetName)) - { - continue; - } - - parameterSetMap[parameterSetName] = parameter; - } - } - else - { - parameterSetMap[ALL_PARAM_SETS_MONIKER] = parameter; - } - } - - // in the rare case, when there are multiply yaml snippets - parameter = parameter.Clone(); - } - - if (!isAtLeastOneYaml) - { - // if no yaml are present it's a special case and we leave it as is - firstParameter = parameter; - } - - // capture these two piece of information - if (firstParameter != null) - { - commmand.Parameters.Add(firstParameter); - _parameterName2ParameterSetMap.Add(Tuple.Create(name, parameterSetMap)); - } - - return true; - } - } -} diff --git a/v1/src/platyPS/platyPS.Resources.psd1 b/v1/src/platyPS/platyPS.Resources.psd1 deleted file mode 100644 index 9e581110..00000000 --- a/v1/src/platyPS/platyPS.Resources.psd1 +++ /dev/null @@ -1,78 +0,0 @@ -# Localized data for en-US - -ConvertFrom-StringData -StringData @' -ModuleNameFromPath = Determined module name for '{0}' as '{1}'. -UpdateDocsForModule = Updating documents for module '{0}' in {1} -CreatingNewMarkdownForCommand = Creating new markdown for command '{0}' -NoMetadataAndMetadata = -NoMetadata and -Metadata parameters cannot be specified at the same time. -CommandNotFound = Command '{0}' not found in the session. -ModuleNotFound = Module '{0}' is not imported in the session. Use "Import-Module -Name {0}" to import module in the current session. -FileNotFound = File '{0}' not found. -ModuleNameNotFoundFromPath = Cannot determine module name for {0}. Use "New-MarkdownHelp -WithModulePage" to create module help. -ModuleOrCommandNotFound = Module '{0}' is not imported in the session or doesn't have any exported commands. -OutputFolderNotFound = The output folder does not exist. -PathIsNotFolder = Path '{0}' is not a folder. -PathIsNotFile = Path '{0}' is not a file. -FileNotFoundSkipping = Path '{0}' not found, skipping. -FilesNotFoundInFolder = Path '{0}' does not contain any files. -NoValidHelpFiles = No valid help files. -FileNotValidHelpFileType = File '{0}' is not a valid help file type. Excluding from Cab file. -AboutFileNotFound = {0} about file not found. -PathNotFound = Path '{0}' not found. -ForAnotherMarkdownAndApplicableTag = [ASSERT] Incorrect usage: cannot pass both -ForAnotherMarkdown and -ApplicableTag -PlatyPS100SchemaDeprecated = PlatyPS schema version 1.0.0 is deprecated and not supported anymore. Please install platyPS 0.7.6 and migrate to the supported version. -CannotWriteFileDirectoryExists = Cannot write file to '{0}', directory with the same name exists. -CannotWriteFileWithoutForce = Cannot write to '{0}', file exists. Use -Force to overwrite. -RangeIsLessThanZero = {0} '{1}' is unsupported: value less than 0 -MetadataDoesNotMatchLength = Metadata for cmdlet '{0}' doesn't match length.\nThis should never happen! Please report the issue on https://github.com/PowerShell/platyPS/issues -FailedSettingFileSystemProvider = PlatyPS Cmdlets only work in the FileSystem Provider. Failed setting provider back to FileSystem. -MoreThanOneGuid = This module has more than one guid. This could impact external help creation. -NoMarkdownFiles = Path '{0}' does not contain any markdown files. -FileContainsMoreThanOneCommand = File '{0}' contains more then one command, skipping upgrade. -OneCommandPerFile = Use 'Update-Markdown -OutputFolder' to convert help to one command per file format first. -CommandNotFoundFileRemoved = Command '{0}' not found in the session, file '{1}' removed. -CommandNotFoundSkippingFile = Command '{0}' not found in the session, skipping upgrade for '{1}'. -CannotFindInMetadataFile = Cannot find '{0}' in metadata for file {1} -PathWillBeUsed = Path '{0}' will be used. -VersionNotFoundForLocale = No version found for Locale '{0}' -ModuleNotFoundFromCommand = {0} Cannot find module for command '{1}' -MultipleModulesFoundFromCommand = {0} Found {1} modules for command '{1}' -ParameterNotFound = {0} Could not find parameter object for '{1}' in command '{2}' -InputMarkdownFile = {0} Input markdown file {1} -SkippingMarkdownFile = {0} Skipping markdown file {1} -WritingYamlToPath = Writing Yaml help to path '{0}' -OutputPathAsFile = {0} Use '{1}' as path to a file. -OutputPathAsDirectory = {0} Use '{1}' as path to a directory. -FilteringForApplicableTag = {0} Filtering for ApplicableTag {1} -WritingExternalHelpToPath = Writing external help to path '{0}' -TestCommandExists = Testing that '{0}' is present on this machine. -FolderNotFoundCreating = Path '{0}' does not exist, creating directory. -CabFileInfo = Creating cab for '{0}', with Guid '{1}', in Locale '{2}' -CreatingCabFileDirectives = Creating Cab file directives. -CreatingCabFile = Creating Cab File. -MovingCabFile = Moving the Cab to the path '{0}' -RemovingExtraCabFileContents = Removing unnecessary Cab file contents. -WritingWithEncoding = Writing to '{0}' with encoding: {1} -ReadingWithEncoding = Reading from '{0}' with encoding = {1} -SettingFileSystemProvider = PlatyPS Cmdlets only work in the FileSystem Provider. PlatyPS is changing the provider of this session back to FileSystem. -ParsingMarkdown = Parsing markdown -Progress = Progress: -Processing = Processing: {0} -HelpVersion = {{ Please enter version of help manually (X.X.X.X) format }} -FwLink = {{ Update Download Link }} -ExampleTitle = Example 1 -ExampleCode = PS C:\\> {{ Add example code here }} -ExampleRemark = {{ Add example description here }} -Description = {{ Fill in the Description }} -ParameterDescription = {{{{ Fill {0} Description }}}} -Synopsis = {{ Fill in the Synopsis }} -Locale = {{ Update Locale }} -Version = {{ Update Help Version }} -ModuleGuid = {{ Update Module Guid }} -Confirm = Prompts you for confirmation before running the cmdlet. -WhatIf = Shows what would happen if the cmdlet runs. The cmdlet is not run. -Skip = Ignores the specified number of objects and then gets the remaining objects. Enter the number of objects to skip. -First = Gets only the specified number of objects. Enter the number of objects to get. -IncludeTotalCount = Reports the total number of objects in the data set (an integer) followed by the selected objects. If the cmdlet cannot determine the total count, it displays "Unknown total count." The integer has an Accuracy property that indicates the reliability of the total count value. The value of Accuracy ranges from 0.0 to 1.0 where 0.0 means that the cmdlet could not count the objects, 1.0 means that the count is exact, and a value between 0.0 and 1.0 indicates an increasingly reliable estimate. -ModuleImporteAutomaticaly = The module {0} was imported automatically. It may cause that parameters will be sorted alphabetically even without usage of the parameter AlphabeticParamsOrder. Please be sure that the loaded module instance contains previously generated help to avoid that. -'@ \ No newline at end of file diff --git a/v1/src/platyPS/platyPS.psd1 b/v1/src/platyPS/platyPS.psd1 deleted file mode 100644 index 9c6f0cca..00000000 --- a/v1/src/platyPS/platyPS.psd1 +++ /dev/null @@ -1,131 +0,0 @@ -# -# Module manifest for module 'platyPS' -# -# Generated by: PowerShell team -# -# Generated on: 2/4/2016 -# - -@{ - -# Script module or binary module file associated with this manifest. -RootModule = 'platyPS.psm1' - -# Version number of this module. -# Do not edit the version. The version is updated by the build script. -ModuleVersion = '0.0.1' - -# ID used to uniquely identify this module -GUID = '0bdcabef-a4b7-4a6d-bf7e-d879817ebbff' - -# Author of this module -Author = 'PowerShell team' - -# Company or vendor of this module -CompanyName = 'Microsoft' - -# Copyright statement for this module -Copyright = '(c) 2016 PowerShell team. All rights reserved.' - -# Description of the functionality provided by this module -Description = 'Generate PowerShell External Help files from Markdown' - -# Minimum version of the Windows PowerShell engine required by this module -# PowerShellVersion = '' - -# Name of the Windows PowerShell host required by this module -# PowerShellHostName = '' - -# Minimum version of the Windows PowerShell host required by this module -# PowerShellHostVersion = '' - -# Minimum version of Microsoft .NET Framework required by this module -# DotNetFrameworkVersion = '' - -# Minimum version of the common language runtime (CLR) required by this module -# CLRVersion = '' - -# Processor architecture (None, X86, Amd64) required by this module -# ProcessorArchitecture = '' - -# Modules that must be imported into the global environment prior to importing this module -# RequiredModules = @() - -# Assemblies that must be loaded prior to importing this module -RequiredAssemblies = @('Markdown.MAML.dll','YamlDotNet.dll') - -# Script files (.ps1) that are run in the caller's environment prior to importing this module. -# ScriptsToProcess = @() - -# Type files (.ps1xml) to be loaded when importing this module -# TypesToProcess = @() - -# Format files (.ps1xml) to be loaded when importing this module -# FormatsToProcess = @() - -# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess -NestedModules = @() - -# Functions to export from this module -FunctionsToExport = @( - 'New-MarkdownHelp', - 'Get-MarkdownMetadata', - 'New-ExternalHelp', - 'New-YamlHelp', - 'Get-HelpPreview', - 'New-ExternalHelpCab', - 'Update-MarkdownHelp', - 'Update-MarkdownHelpModule', - 'New-MarkdownAboutHelp', - 'Merge-MarkdownHelp' -) - -# Cmdlets to export from this module -CmdletsToExport = @() - -# Variables to export from this module -VariablesToExport = @() - -# Aliases to export from this module -AliasesToExport = @() - -# DSC resources to export from this module -# DscResourcesToExport = @() - -# List of all modules packaged with this module -# ModuleList = @() - -# List of all files packaged with this module -# FileList = @() - -# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. -PrivateData = @{ - - PSData = @{ - - # Tags applied to this module. These help with module discovery in online galleries. - Tags = @('help', 'markdown', 'MAML', 'PSEdition_Core', 'PSEdition_Desktop') - - # A URL to the license for this module. - LicenseUri = 'https://github.com/PowerShell/platyPS/blob/master/LICENSE' - - # A URL to the main website for this project. - ProjectUri = 'https://github.com/PowerShell/platyPS' - - # A URL to an icon representing this module. - # IconUri = '' - - # ReleaseNotes of this module - # ReleaseNotes = '' - - } # End of PSData hashtable - -} # End of PrivateData hashtable - -# HelpInfo URI of this module -HelpInfoURI = 'https://aka.ms/ps-modules-help' - -# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. -# DefaultCommandPrefix = '' - -} diff --git a/v1/src/platyPS/platyPS.psm1 b/v1/src/platyPS/platyPS.psm1 deleted file mode 100644 index 763023db..00000000 --- a/v1/src/platyPS/platyPS.psm1 +++ /dev/null @@ -1,3112 +0,0 @@ -#region PlatyPS - -## DEVELOPERS NOTES & CONVENTIONS -## -## 1. Non-exported functions (subroutines) should avoid using -## PowerShell standard Verb-Noun naming convention. -## They should use camalCase or PascalCase instead. -## 2. SMALL subroutines, used only from ONE function -## should be placed inside the parent function body. -## They should use camalCase for the name. -## 3. LARGE subroutines and subroutines used from MORE THEN ONE function -## should be placed after the IMPLEMENTATION text block in the middle -## of this module. -## They should use PascalCase for the name. -## 4. Add comment "# yeild" on subroutine calls that write values to pipeline. -## It would help keep code maintainable and simplify ramp up for others. -## - -Import-LocalizedData -BindingVariable LocalizedData -FileName platyPS.Resources.psd1 - -## Script constants - -$script:EXTERNAL_HELP_FILE_YAML_HEADER = 'external help file' -$script:ONLINE_VERSION_YAML_HEADER = 'online version' -$script:SCHEMA_VERSION_YAML_HEADER = 'schema' -$script:APPLICABLE_YAML_HEADER = 'applicable' - -$script:UTF8_NO_BOM = New-Object System.Text.UTF8Encoding -ArgumentList $False -$script:SET_NAME_PLACEHOLDER = 'UNNAMED_PARAMETER_SET' -# TODO: this is just a place-holder, we can do better -$script:DEFAULT_MAML_XML_OUTPUT_NAME = 'rename-me-help.xml' - -$script:MODULE_PAGE_MODULE_NAME = "Module Name" -$script:MODULE_PAGE_GUID = "Module Guid" -$script:MODULE_PAGE_LOCALE = "Locale" -$script:MODULE_PAGE_FW_LINK = "Download Help Link" -$script:MODULE_PAGE_HELP_VERSION = "Help Version" -$script:MODULE_PAGE_ADDITIONAL_LOCALE = "Additional Locale" - -$script:MAML_ONLINE_LINK_DEFAULT_MONIKER = 'Online Version:' - -function New-MarkdownHelp -{ - [CmdletBinding()] - [OutputType([System.IO.FileInfo[]])] - param( - [Parameter(Mandatory=$true, - ValueFromPipeline=$true, - ParameterSetName="FromModule")] - [string[]]$Module, - - [Parameter(Mandatory=$true, - ParameterSetName="FromCommand")] - [string[]]$Command, - - [Parameter(Mandatory=$true, - ParameterSetName="FromMaml")] - [string[]]$MamlFile, - - [Parameter(ParameterSetName="FromModule")] - [Parameter(ParameterSetName="FromCommand")] - [System.Management.Automation.Runspaces.PSSession]$Session, - - [Parameter(ParameterSetName="FromMaml")] - [switch]$ConvertNotesToList, - - [Parameter(ParameterSetName="FromMaml")] - [switch]$ConvertDoubleDashLists, - - [switch]$Force, - - [switch]$AlphabeticParamsOrder, - - [hashtable]$Metadata, - - [Parameter(ParameterSetName="FromCommand")] - [string]$OnlineVersionUrl = '', - - [Parameter(Mandatory=$true)] - [string]$OutputFolder, - - [switch]$NoMetadata, - - [switch]$UseFullTypeName, - - [System.Text.Encoding]$Encoding = $script:UTF8_NO_BOM, - - [Parameter(ParameterSetName="FromModule")] - [Parameter(ParameterSetName="FromMaml")] - [switch]$WithModulePage, - - [Parameter(ParameterSetName="FromModule")] - [Parameter(ParameterSetName="FromMaml")] - [string]$ModulePagePath, - - [Parameter(ParameterSetName="FromModule")] - [Parameter(ParameterSetName="FromMaml")] - [string] - $Locale = "en-US", - - [Parameter(ParameterSetName="FromModule")] - [Parameter(ParameterSetName="FromMaml")] - [string] - $HelpVersion = $LocalizedData.HelpVersion, - - [Parameter(ParameterSetName="FromModule")] - [Parameter(ParameterSetName="FromMaml")] - [string] - $FwLink = $LocalizedData.FwLink, - - [Parameter(ParameterSetName="FromMaml")] - [string] - $ModuleName = "MamlModule", - - [Parameter(ParameterSetName="FromMaml")] - [string] - $ModuleGuid = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", - - [switch] - $ExcludeDontShow - ) - - begin - { - validateWorkingProvider - New-Item -Type Directory $OutputFolder -ErrorAction SilentlyContinue > $null - } - - process - { - function updateMamlObject - { - param( - [Parameter(Mandatory=$true)] - [Markdown.MAML.Model.MAML.MamlCommand]$MamlCommandObject - ) - - # - # Here we define our misc template for new markdown to bootstrape easier - # - - # Example - if ($MamlCommandObject.Examples.Count -eq 0) - { - $MamlExampleObject = New-Object -TypeName Markdown.MAML.Model.MAML.MamlExample - - $MamlExampleObject.Title = $LocalizedData.ExampleTitle - $MamlExampleObject.Code = @( - New-Object -TypeName Markdown.MAML.Model.MAML.MamlCodeBlock ($LocalizedData.ExampleCode, 'powershell') - ) - $MamlExampleObject.Remarks = $LocalizedData.ExampleRemark - - $MamlCommandObject.Examples.Add($MamlExampleObject) - } - - if ($AlphabeticParamsOrder) - { - SortParamsAlphabetically $MamlCommandObject - } - } - - function processMamlObjectToFile - { - param( - [Parameter(ValueFromPipeline=$true)] - [ValidateNotNullOrEmpty()] - [Markdown.MAML.Model.MAML.MamlCommand]$mamlObject - ) - - process - { - # populate template - updateMamlObject $mamlObject - if (-not $OnlineVersionUrl) - { - # if it's not passed, we should get it from the existing help - $onlineLink = $mamlObject.Links | Select-Object -First 1 - if ($onlineLink) - { - $online = $onlineLink.LinkUri - if ($onlineLink.LinkName -eq $script:MAML_ONLINE_LINK_DEFAULT_MONIKER -or $onlineLink.LinkName -eq $onlineLink.LinkUri) - { - # if links follow standart MS convention or doesn't have name, - # remove it to avoid duplications - $mamlObject.Links.Remove($onlineLink) > $null - } - } - } - else - { - $online = $OnlineVersionUrl - } - - $commandName = $mamlObject.Name - - # create markdown - if ($NoMetadata) - { - $newMetadata = $null - } - else - { - # get help file name - if ($MamlFile) - { - $helpFileName = Split-Path -Leaf $MamlFile - } - else - { - # Get-Command requires that script input be a path - if ($mamlObject.Name.EndsWith(".ps1")) - { - $getCommandName = Resolve-Path $Command - } - # For cmdlets, nothing needs to be done - else - { - $getCommandName = $commandName - } - - $a = @{ - Name = $getCommandName - } - if ($module) { - # for module case, scope it just to this module - $a['Module'] = $module - } - - $helpFileName = GetHelpFileName (Get-Command @a) - } - - Write-Verbose "Maml things module is: $($mamlObject.ModuleName)" - - $newMetadata = ($Metadata + @{ - $script:EXTERNAL_HELP_FILE_YAML_HEADER = $helpFileName - $script:ONLINE_VERSION_YAML_HEADER = $online - $script:MODULE_PAGE_MODULE_NAME = $mamlObject.ModuleName - }) - } - - $md = ConvertMamlModelToMarkdown -mamlCommand $mamlObject -metadata $newMetadata -NoMetadata:$NoMetadata - - MySetContent -path (Join-Path $OutputFolder "$commandName.md") -value $md -Encoding $Encoding -Force:$Force - } - } - - if ($NoMetadata -and $Metadata) - { - throw $LocalizedData.NoMetadataAndMetadata - } - - if ($PSCmdlet.ParameterSetName -eq 'FromCommand') - { - $command | ForEach-Object { - if (-not (Get-Command $_ -ErrorAction SilentlyContinue)) - { - throw $LocalizedData.CommandNotFound -f $_ - } - - GetMamlObject -Session $Session -Cmdlet $_ -UseFullTypeName:$UseFullTypeName -ExcludeDontShow:$ExcludeDontShow.IsPresent | processMamlObjectToFile - } - } - else - { - if ($module) - { - $iterator = $module - } - else - { - $iterator = $MamlFile - } - - $iterator | ForEach-Object { - if ($PSCmdlet.ParameterSetName -eq 'FromModule') - { - if (-not (GetCommands -AsNames -module $_)) - { - throw $LocalizedData.ModuleNotFound -f $_ - } - - GetMamlObject -Session $Session -Module $_ -UseFullTypeName:$UseFullTypeName -ExcludeDontShow:$ExcludeDontShow.IsPresent | processMamlObjectToFile - - $ModuleName = $_ - $ModuleGuid = (Get-Module $ModuleName).Guid - $CmdletNames = GetCommands -AsNames -Module $ModuleName - } - else # 'FromMaml' - { - if (-not (Test-Path $_)) - { - throw $LocalizedData.FileNotFound -f $_ - } - - GetMamlObject -MamlFile $_ -ConvertNotesToList:$ConvertNotesToList -ConvertDoubleDashLists:$ConvertDoubleDashLists -ExcludeDontShow:$ExcludeDontShow.IsPresent | processMamlObjectToFile - - $CmdletNames += GetMamlObject -MamlFile $_ -ExcludeDontShow:$ExcludeDontShow.IsPresent | ForEach-Object {$_.Name} - } - - if($WithModulePage) - { - if(-not $ModuleGuid) - { - $ModuleGuid = "00000000-0000-0000-0000-000000000000" - } - if($ModuleGuid.Count -gt 1) - { - Write-Warning -Message $LocalizedData.MoreThanOneGuid - } - # yeild - NewModuleLandingPage -Path $OutputFolder ` - -ModulePagePath $ModulePagePath ` - -ModuleName $ModuleName ` - -ModuleGuid $ModuleGuid ` - -CmdletNames $CmdletNames ` - -Locale $Locale ` - -Version $HelpVersion ` - -FwLink $FwLink ` - -Encoding $Encoding ` - -Force:$Force - } - } - } - } -} - - -function Get-MarkdownMetadata -{ - [CmdletBinding(DefaultParameterSetName="FromPath")] - - param( - [Parameter(Mandatory=$true, - ValueFromPipeline=$true, - ValueFromPipelineByPropertyName=$true, - Position=1, - ParameterSetName="FromPath")] - [SupportsWildcards()] - [string[]]$Path, - - [Parameter(Mandatory=$true, - ParameterSetName="FromMarkdownString")] - [string]$Markdown - ) - - process - { - if ($PSCmdlet.ParameterSetName -eq 'FromMarkdownString') - { - return [Markdown.MAML.Parser.MarkdownParser]::GetYamlMetadata($Markdown) - } - else # FromFile) - { - GetMarkdownFilesFromPath $Path -IncludeModulePage | ForEach-Object { - $md = Get-Content -Raw $_.FullName - [Markdown.MAML.Parser.MarkdownParser]::GetYamlMetadata($md) # yeild - } - } - } -} - -function Update-MarkdownHelp -{ - [CmdletBinding()] - [OutputType([System.IO.FileInfo[]])] - param( - [Parameter(Mandatory=$true, - ValueFromPipeline=$true)] - [SupportsWildcards()] - [string[]]$Path, - - [System.Text.Encoding]$Encoding = $script:UTF8_NO_BOM, - - [string]$LogPath, - [switch]$LogAppend, - [switch]$AlphabeticParamsOrder, - [switch]$UseFullTypeName, - [switch]$UpdateInputOutput, - [Switch]$Force, - [System.Management.Automation.Runspaces.PSSession]$Session, - [switch]$ExcludeDontShow - ) - - begin - { - validateWorkingProvider - $infoCallback = GetInfoCallback $LogPath -Append:$LogAppend - $MarkdownFiles = @() - } - - process - { - $MarkdownFiles += GetMarkdownFilesFromPath $Path - } - - end - { - function log - { - param( - [string]$message, - [switch]$warning - ) - - $message = "[Update-MarkdownHelp] $([datetime]::now) $message" - if ($warning) - { - Write-Warning $message - } - - $infoCallback.Invoke($message) - } - - if (-not $MarkdownFiles) - { - log -warning ($LocalizedData.NoMarkdownFiles -f $Path) - return - } - - - $MarkdownFiles | ForEach-Object { - $file = $_ - - $filePath = $file.FullName - $oldModels = GetMamlModelImpl $filePath -ForAnotherMarkdown -Encoding $Encoding - - if ($oldModels.Count -gt 1) - { - log -warning ($LocalizedData.FileContainsMoreThanOneCommand -f $filePath) - log -warning $LocalizedData.OneCommandPerFile - return - } - - $oldModel = $oldModels[0] - - $name = $oldModel.Name - [Array]$loadedModulesBefore = $(Get-Module | Select-Object -Property Name) - $command = Get-Command $name -ErrorAction SilentlyContinue - if (-not $command) - { - if ($Force) { - if (Test-Path $filePath) { - Remove-Item -Path $filePath -Confirm:$false - log -warning ($LocalizedData.CommandNotFoundFileRemoved -f $name, $filePath) - return - } - } else { - log -warning ($LocalizedData.CommandNotFoundSkippingFile -f $name, $filePath) - return - } - } - elseif (($null -ne $command.ModuleName) -and ($loadedModulesBefore.Name -notcontains $command.ModuleName)) - { - log -warning ($LocalizedData.ModuleImporteAutomaticaly -f $($command.ModuleName)) - } - - # update the help file entry in the metadata - $metadata = Get-MarkdownMetadata $filePath - $metadata["external help file"] = GetHelpFileName $command - $reflectionModel = GetMamlObject -Session $Session -Cmdlet $name -UseFullTypeName:$UseFullTypeName -ExcludeDontShow:$ExcludeDontShow.IsPresent - $metadata[$script:MODULE_PAGE_MODULE_NAME] = $reflectionModel.ModuleName - - $merger = New-Object Markdown.MAML.Transformer.MamlModelMerger -ArgumentList $infoCallback - $newModel = $merger.Merge($reflectionModel, $oldModel, $UpdateInputOutput) - - if ($AlphabeticParamsOrder) - { - SortParamsAlphabetically $newModel - } - - $md = ConvertMamlModelToMarkdown -mamlCommand $newModel -metadata $metadata -PreserveFormatting - MySetContent -path $file.FullName -value $md -Encoding $Encoding -Force # yield - } - } -} - -function Merge-MarkdownHelp -{ - [CmdletBinding()] - [OutputType([System.IO.FileInfo[]])] - param( - [Parameter(Mandatory=$true, - ValueFromPipeline=$true)] - [SupportsWildcards()] - [string[]]$Path, - - [Parameter(Mandatory=$true)] - [string]$OutputPath, - - [System.Text.Encoding]$Encoding = $script:UTF8_NO_BOM, - - [Switch]$ExplicitApplicableIfAll, - - [Switch]$Force, - - [string]$MergeMarker = "!!! " - ) - - begin - { - validateWorkingProvider - $MarkdownFiles = @() - } - - process - { - $MarkdownFiles += GetMarkdownFilesFromPath $Path - } - - end - { - function log - { - param( - [string]$message, - [switch]$warning - ) - - $message = "[Update-MarkdownHelp] $([datetime]::now) $message" - if ($warning) - { - Write-Warning $message - } - else - { - Write-Verbose $message - } - } - - if (-not $MarkdownFiles) - { - log -warning ($LocalizedData.NoMarkdownFiles -f $Path) - return - } - - function getTags - { - param($files) - - ($files | Split-Path | Split-Path -Leaf | Group-Object).Name - } - - # use parent folder names as tags - $allTags = getTags $MarkdownFiles - log "Using following tags for the merge: $tags" - $fileGroups = $MarkdownFiles | Group-Object -Property Name - log "Found $($fileGroups.Count) file groups" - - $fileGroups | ForEach-Object { - $files = $_.Group - $groupName = $_.Name - - $dict = New-Object 'System.Collections.Generic.Dictionary[string, Markdown.MAML.Model.MAML.MamlCommand]' - $files | ForEach-Object { - $model = GetMamlModelImpl $_.FullName -ForAnotherMarkdown -Encoding $Encoding - # unwrap List of 1 element - $model = $model[0] - $tag = getTags $_ - log "Adding tag $tag and $model" - $dict[$tag] = $model - } - - $tags = $dict.Keys - if (($allTags | measure-object).Count -gt ($tags | measure-object).Count -or $ExplicitApplicableIfAll) - { - $newMetadata = @{ $script:APPLICABLE_YAML_HEADER = $tags -join ', ' } - } - else - { - $newMetadata = @{} - } - - $merger = New-Object Markdown.MAML.Transformer.MamlMultiModelMerger -ArgumentList $null, (-not $ExplicitApplicableIfAll), $MergeMarker - $newModel = $merger.Merge($dict) - - $md = ConvertMamlModelToMarkdown -mamlCommand $newModel -metadata $newMetadata -PreserveFormatting - $outputFilePath = Join-Path $OutputPath $groupName - MySetContent -path $outputFilePath -value $md -Encoding $Encoding -Force:$Force # yeild - } - } -} - -function Update-MarkdownHelpModule -{ - [CmdletBinding()] - [OutputType([System.IO.FileInfo[]])] - param( - [Parameter(Mandatory=$true, - ValueFromPipeline=$true)] - [SupportsWildcards()] - [string[]]$Path, - - [System.Text.Encoding]$Encoding = $script:UTF8_NO_BOM, - [switch]$RefreshModulePage, - [string]$ModulePagePath, - [string]$LogPath, - [switch]$LogAppend, - [switch]$AlphabeticParamsOrder, - [switch]$UseFullTypeName, - [switch]$UpdateInputOutput, - [switch]$Force, - [System.Management.Automation.Runspaces.PSSession]$Session, - [switch]$ExcludeDontShow - ) - - begin - { - validateWorkingProvider - $infoCallback = GetInfoCallback $LogPath -Append:$LogAppend - $MarkdownFiles = @() - } - - process - { - } - - end - { - function log - { - param( - [string]$message, - [switch]$warning - ) - - $message = "[Update-MarkdownHelpModule] $([datetime]::now) $message" - if ($warning) - { - Write-Warning $message - } - - $infoCallback.Invoke($message) - } - - foreach ($modulePath in $Path) - { - $module = $null - $h = Get-MarkdownMetadata -Path $modulePath - # this is pretty hacky and would lead to errors - # the idea is to find module name from landing page when it's available - if ($h.$script:MODULE_PAGE_MODULE_NAME) - { - $module = $h.$script:MODULE_PAGE_MODULE_NAME | Select-Object -First 1 - log ($LocalizedData.ModuleNameFromPath -f $modulePath, $module) - } - - if (-not $module) - { - Write-Error -Message ($LocalizedData.ModuleNameNotFoundFromPath -f $modulePath) - continue - } - - # always append on this call - log ("[Update-MarkdownHelpModule]" + (Get-Date).ToString()) - log ($LocalizedData.UpdateDocsForModule -f $module, $modulePath) - $affectedFiles = Update-MarkdownHelp -Session $Session -Path $modulePath -LogPath $LogPath -LogAppend -Encoding $Encoding -AlphabeticParamsOrder:$AlphabeticParamsOrder -UseFullTypeName:$UseFullTypeName -UpdateInputOutput:$UpdateInputOutput -Force:$Force -ExcludeDontShow:$ExcludeDontShow - $affectedFiles # yeild - - $allCommands = GetCommands -AsNames -Module $Module - if (-not $allCommands) - { - throw $LocalizedData.ModuleOrCommandNotFound -f $Module - } - - $updatedCommands = $affectedFiles.BaseName - $allCommands | ForEach-Object { - if ( -not ($updatedCommands -contains $_) ) - { - log ($LocalizedData.CreatingNewMarkdownForCommand -f $_) - $newFiles = New-MarkdownHelp -Command $_ -OutputFolder $modulePath -AlphabeticParamsOrder:$AlphabeticParamsOrder -Force:$Force -ExcludeDontShow:$ExcludeDontShow - $newFiles # yeild - } - } - - if($RefreshModulePage) - { - $MamlModel = New-Object System.Collections.Generic.List[Markdown.MAML.Model.MAML.MamlCommand] - $files = @() - $MamlModel = GetMamlModelImpl $affectedFiles -ForAnotherMarkdown -Encoding $Encoding - NewModuleLandingPage -RefreshModulePage -ModulePagePath $ModulePagePath -Path $modulePath -ModuleName $module -Module $MamlModel -Encoding $Encoding -Force - } - } - } -} - -function New-MarkdownAboutHelp -{ - [CmdletBinding()] - param( - [Parameter(Mandatory=$true)] - [string] $OutputFolder, - [string] $AboutName - ) - - begin - { - if ($AboutName.StartsWith('about_')) { $AboutName = $AboutName.Substring('about_'.Length)} - validateWorkingProvider - $templatePath = Join-Path $PSScriptRoot "templates\aboutTemplate.md" - } - - process - { - if(Test-Path $OutputFolder) - { - $AboutContent = Get-Content $templatePath - $AboutContent = $AboutContent.Replace("{{FileNameForHelpSystem}}",("about_" + $AboutName)) - $AboutContent = $AboutContent.Replace("{{TOPIC NAME}}",$AboutName) - $NewAboutTopic = New-Item -Path $OutputFolder -Name "about_$($AboutName).md" - Set-Content -Value $AboutContent -Path $NewAboutTopic -Encoding UTF8 - } - else - { - throw $LocalizedData.OutputFolderNotFound - } - } -} - -function New-YamlHelp -{ - [CmdletBinding()] - [OutputType([System.IO.FileInfo[]])] - param( - [Parameter(Mandatory=$true, - Position=1, - ValueFromPipeline=$true, - ValueFromPipelineByPropertyName=$true)] - [string[]]$Path, - - [Parameter(Mandatory=$true)] - [string]$OutputFolder, - - [System.Text.Encoding]$Encoding = [System.Text.Encoding]::UTF8, - - [switch]$Force - ) - begin - { - validateWorkingProvider - - $MarkdownFiles = @() - - if(-not (Test-Path $OutputFolder)) - { - New-Item -Type Directory $OutputFolder -ErrorAction SilentlyContinue > $null - } - - if(-not (Test-Path -PathType Container $OutputFolder)) - { - throw $LocalizedData.PathIsNotFolder -f $OutputFolder - } - } - process - { - $MarkdownFiles += GetMarkdownFilesFromPath $Path - } - end - { - $MarkdownFiles | ForEach-Object { - Write-Verbose -Message ($LocalizedData.InputMarkdownFile -f '[New-YamlHelp]', $_) - } - - foreach($markdownFile in $MarkdownFiles) - { - $mamlModels = GetMamlModelImpl $markdownFile.FullName -Encoding $Encoding - foreach($mamlModel in $mamlModels) - { - $markdownMetadata = Get-MarkdownMetadata -Path $MarkdownFile.FullName - - ## We set the module here in the PowerShell since the Yaml block is not read by the parser - $mamlModel.ModuleName = $markdownMetadata[$script:MODULE_PAGE_MODULE_NAME] - - $yaml = [Markdown.MAML.Renderer.YamlRenderer]::MamlModelToString($mamlModel) - $outputFilePath = Join-Path $OutputFolder ($mamlModel.Name + ".yml") - Write-Verbose -Message ($LocalizedData.WritingYamlToPath -f $outputFilePath) - MySetContent -Path $outputFilePath -Value $yaml -Encoding $Encoding -Force:$Force - } - } - } -} - -function New-ExternalHelp -{ - [CmdletBinding()] - [OutputType([System.IO.FileInfo[]])] - param( - [Parameter(Mandatory=$true, - Position=1, - ValueFromPipeline=$true, - ValueFromPipelineByPropertyName=$true)] - [SupportsWildcards()] - [string[]]$Path, - - [Parameter(Mandatory=$true)] - [string]$OutputPath, - - [string[]]$ApplicableTag, - - [System.Text.Encoding]$Encoding = [System.Text.Encoding]::UTF8, - - [ValidateRange(80, [int]::MaxValue)] - [int] $MaxAboutWidth = 80, - - [string]$ErrorLogFile, - - [switch]$Force, - - [switch]$ShowProgress - ) - - begin - { - validateWorkingProvider - - $MarkdownFiles = @() - $AboutFiles = @() - $IsOutputContainer = $true - if ( $OutputPath.EndsWith('.xml') -and (-not (Test-Path -PathType Container $OutputPath )) ) - { - $IsOutputContainer = $false - Write-Verbose -Message ($LocalizedData.OutputPathAsFile -f '[New-ExternalHelp]', $OutputPath) - } - else - { - New-Item -Type Directory $OutputPath -ErrorAction SilentlyContinue > $null - Write-Verbose -Message ($LocalizedData.OutputPathAsDirectory -f '[New-ExternalHelp]', $OutputPath) - } - - if ( -not $ShowProgress -or $(Get-Variable -Name IsCoreClr -ValueOnly -ErrorAction SilentlyContinue) ) - { - Function Write-Progress() {} - } - } - - process - { - $MarkdownFiles += GetMarkdownFilesFromPath $Path - - if($MarkdownFiles) - { - $AboutFiles += GetAboutTopicsFromPath -Path $Path -MarkDownFilesAlreadyFound $MarkdownFiles.FullName - } - else - { - $AboutFiles += GetAboutTopicsFromPath -Path $Path - } - } - - end - { - # Tracks all warnings and errors - $warningsAndErrors = New-Object System.Collections.Generic.List[System.Object] - - try { - # write verbose output and filter out files based on applicable tag - $MarkdownFiles | ForEach-Object { - Write-Verbose -Message ($LocalizedData.InputMarkdownFile -f '[New-ExternalHelp]', $_) - } - - if ($ApplicableTag) { - Write-Verbose -Message ($LocalizedData.FilteringForApplicableTag -f '[New-ExternalHelp]', $ApplicableTag) - $MarkdownFiles = $MarkdownFiles | ForEach-Object { - $applicableList = GetApplicableList -Path $_.FullName - # this Compare-Object call is getting the intersection of two string[] - if ((-not $applicableList) -or (Compare-Object $applicableList $ApplicableTag -IncludeEqual -ExcludeDifferent)) { - # yeild - $_ - } - else { - Write-Verbose -Message ($LocalizedData.SkippingMarkdownFile -f '[New-ExternalHelp]', $_) - } - } - } - - # group the files based on the output xml path metadata tag - if ($IsOutputContainer) { - $defaultPath = Join-Path $OutputPath $script:DEFAULT_MAML_XML_OUTPUT_NAME - $groups = $MarkdownFiles | Group-Object { - $h = Get-MarkdownMetadata -Path $_.FullName - if ($h -and $h[$script:EXTERNAL_HELP_FILE_YAML_HEADER]) { - Join-Path $OutputPath $h[$script:EXTERNAL_HELP_FILE_YAML_HEADER] - } - else { - $msgLine1 = $LocalizedData.CannotFindInMetadataFile -f $script:EXTERNAL_HELP_FILE_YAML_HEADER, $_.FullName - $msgLine2 = $LocalizedData.PathWillBeUsed -f $defaultPath - $warningsAndErrors.Add(@{ - Severity = "Warning" - Message = "$msgLine1 $msgLine2" - FilePath = "$($_.FullName)" - }) - - Write-Warning -Message "[New-ExternalHelp] $msgLine1" - Write-Warning -Message "[New-ExternalHelp] $msgLine2" - $defaultPath - } - } - } - else { - $groups = $MarkdownFiles | Group-Object { $OutputPath } - } - - # generate the xml content - $r = new-object -TypeName 'Markdown.MAML.Renderer.MamlRenderer' - - foreach ($group in $groups) { - $maml = GetMamlModelImpl ($group.Group | ForEach-Object {$_.FullName}) -Encoding $Encoding -ApplicableTag $ApplicableTag - $xml = $r.MamlModelToString($maml) - - $outPath = $group.Name # group name - Write-Verbose -Message ($LocalizedData.WritingExternalHelpToPath -f $outPath) - MySetContent -Path $outPath -Value $xml -Encoding $Encoding -Force:$Force - } - - # handle about topics - if ($AboutFiles.Count -gt 0) { - foreach ($About in $AboutFiles) { - $r = New-Object -TypeName 'Markdown.MAML.Renderer.TextRenderer' -ArgumentList($MaxAboutWidth) - $Content = Get-Content -Raw $About.FullName - $p = NewMarkdownParser - $model = $p.ParseString($Content) - $value = $r.AboutMarkDownToString($model) - - $outPath = Join-Path $OutputPath ([io.path]::GetFileNameWithoutExtension($About.FullName) + ".help.txt") - if (!(Split-Path -Leaf $outPath).ToUpper().StartsWith("ABOUT_", $true, $null)) { - $outPath = Join-Path (Split-Path -Parent $outPath) ("about_" + (Split-Path -Leaf $outPath)) - } - MySetContent -Path $outPath -Value $value -Encoding $Encoding -Force:$Force - } - } - } - catch { - # Log error and rethrow - $warningsAndErrors.Add(@{ - Severity = "Error" - Message = "$_.Exception.Message" - FilePath = "" - }) - - throw - } - finally { - if ($ErrorLogFile) { - ConvertTo-Json $warningsAndErrors | Out-File $ErrorLogFile - } - } - } -} - -function Get-HelpPreview -{ - [CmdletBinding()] - [OutputType('MamlCommandHelpInfo')] - param( - [Parameter(Mandatory=$true, - ValueFromPipeline=$true, - Position=1)] - [SupportsWildcards()] - [string[]]$Path, - - [switch]$ConvertNotesToList, - [switch]$ConvertDoubleDashLists - ) - - process - { - foreach ($MamlFilePath in $Path) - { - if (-not (Test-path -Type Leaf $MamlFilePath)) - { - Write-Error -Message ($LocalizedData.FileNotFoundSkipping -f $MamlFilePath) - continue - } - - # this is Resolve-Path that resolves mounted drives (i.e. good for tests) - $MamlFilePath = (Get-ChildItem $MamlFilePath).FullName - - # Read the malm file - $xml = [xml](Get-Content $MamlFilePath -Raw -ea SilentlyContinue) - if (-not $xml) - { - # already error-out on the convertion, no need to repeat ourselves - continue - } - - # we need a copy of maml file to bypass powershell cache, - # in case we reuse the same filename few times. - $MamlCopyPath = [System.IO.Path]::GetTempFileName() - try - { - if ($ConvertDoubleDashLists) - { - $p = $xml.GetElementsByTagName('maml:para') | ForEach-Object { - # Convert "-- "-lists into "- "-lists - # to make them markdown compatible - # as described in https://github.com/PowerShell/platyPS/issues/117 - $newInnerXml = $_.get_InnerXml() -replace "(`n|^)-- ", '$1- ' - $_.set_InnerXml($newInnerXml) - } - } - - if ($ConvertNotesToList) - { - # Add inline bullet-list, as described in https://github.com/PowerShell/platyPS/issues/125 - $xml.helpItems.command.alertSet.alert | - ForEach-Object { - # make first <para> a list item - # add indentations to other <para> to make them continuation of list item - $_.ChildNodes | Select-Object -First 1 | - ForEach-Object { - $newInnerXml = '* ' + $_.get_InnerXml() - $_.set_InnerXml($newInnerXml) - } - - $_.ChildNodes | Select-Object -Skip 1 | - ForEach-Object { - # this character is not a valid space. - # We have to use some odd character here, becasue help engine strips out - # all legetimate whitespaces. - # Note: powershell doesn't render it properly, it will appear as a non-writable char. - $newInnerXml = ([string][char]0xc2a0) * 2 + $_.get_InnerXml() - $_.set_InnerXml($newInnerXml) - } - } - } - - # in PS v5 help engine is not happy, when first non-empty link (== Online version link) is not a valid URI - # User encounter this problem too oftern to ignore it, hence this workaround in platyPS: - # always add a dummy link with a valid URI into xml and then remove the first link from the help object. - # for more context see https://github.com/PowerShell/platyPS/issues/144 - $xml.helpItems.command.relatedLinks | ForEach-Object { - if ($_) - { - $_.InnerXml = '<maml:navigationLink xmlns:maml="http://schemas.microsoft.com/maml/2004/10"><maml:linkText>PLATYPS_DUMMY_LINK</maml:linkText><maml:uri>https://github.com/PowerShell/platyPS/issues/144</maml:uri></maml:navigationLink>' + $_.InnerXml - } - } - - $xml.Save($MamlCopyPath) - - foreach ($command in $xml.helpItems.command.details.name) - { - #PlatyPS will have trouble parsing a command with space around the name. - $command = $command.Trim() - $thisDefinition = @" - -<# -.ExternalHelp $MamlCopyPath -#> -filter $command -{ - [CmdletBinding()] - Param - ( - [Parameter(Mandatory=`$true)] - [switch]`$platyPSHijack - ) - - Microsoft.PowerShell.Utility\Write-Warning 'PlatyPS hijacked your command $command.' - Microsoft.PowerShell.Utility\Write-Warning 'We are sorry for that. It means, there is a bug in our Get-HelpPreview logic.' - Microsoft.PowerShell.Utility\Write-Warning 'Please report this issue https://github.com/PowerShell/platyPS/issues' - Microsoft.PowerShell.Utility\Write-Warning 'Restart PowerShell to fix the problem.' -} - -# filter is rare enough to distinguish with other commands -`$innerHelp = Microsoft.PowerShell.Core\Get-Help $command -Full -Category filter - -Microsoft.PowerShell.Core\Export-ModuleMember -Function @() -"@ - $m = New-Module ( [scriptblock]::Create( "$thisDefinition" )) - $help = & $m { $innerHelp } - # this is the second part of the workaround for https://github.com/PowerShell/platyPS/issues/144 - # see comments above for context - $help.relatedLinks | ForEach-Object { - if ($_) - { - $_.navigationLink = $_.navigationLink | Select-Object -Skip 1 - } - } - $help # yeild - } - } - finally - { - Remove-Item $MamlCopyPath - } - } - } -} - - -function New-ExternalHelpCab -{ - [Cmdletbinding()] - param( - [parameter(Mandatory=$true)] - [ValidateScript( - { - if(Test-Path $_ -PathType Container) - { - $True - } - else - { - Throw $LocalizedData.PathIsNotFolder -f $_ - } - })] - [string] $CabFilesFolder, - [parameter(Mandatory=$true)] - [ValidateScript( - { - if(Test-Path $_ -PathType Leaf) - { - $True - } - else - { - Throw $LocalizedData.PathIsNotFile -f $_ - } - })] - [string] $LandingPagePath, - [parameter(Mandatory=$true)] - [string] $OutputFolder, - - [parameter()] - [switch] $IncrementHelpVersion - ) - begin - { - validateWorkingProvider - New-Item -Type Directory $OutputFolder -ErrorAction SilentlyContinue > $null - } - process - { - #Testing for MakeCab.exe - Write-Verbose -Message ($LocalizedData.TestCommandExists -f 'MakeCab.exe') - $MakeCab = Get-Command MakeCab - if(-not $MakeCab) - { - throw $LocalizedData.CommandNotFound -f 'MakeCab.exe' - } - #Testing for files in source directory - if((Get-ChildItem -Path $CabFilesFolder).Count -le 0) - { - throw $LocalizedData.FilesNotFoundInFolder -f $CabFilesFolder - } - #Testing for valid help file types - $ValidHelpFileTypes = '.xml', '.txt' - $HelpFiles = Get-ChildItem -Path $CabFilesFolder -File - $ValidHelpFiles = $HelpFiles | Where-Object { $_.Extension -in $ValidHelpFileTypes } - $InvalidHelpFiles = $HelpFiles | Where-Object { $_.Extension -notin $ValidHelpFileTypes } - if(-not $ValidHelpFiles) - { - throw $LocalizedData.NoValidHelpFiles - } - if($InvalidHelpFiles) - { - $InvalidHelpFiles | ForEach-Object { Write-Warning -Message ($LocalizedData.FileNotValidHelpFileType -f $_.FullName) } - } - - - ###Get Yaml Metadata here - $Metadata = Get-MarkdownMetadata -Path $LandingPagePath - - $ModuleName = $Metadata[$script:MODULE_PAGE_MODULE_NAME] - $Guid = $Metadata[$script:MODULE_PAGE_GUID] - $Locale = $Metadata[$script:MODULE_PAGE_LOCALE] - $FwLink = $Metadata[$script:MODULE_PAGE_FW_LINK] - $OldHelpVersion = $Metadata[$script:MODULE_PAGE_HELP_VERSION] - $AdditionalLocale = $Metadata[$script:MODULE_PAGE_ADDITIONAL_LOCALE] - - if($IncrementHelpVersion) - { - #IncrementHelpVersion - $HelpVersion = IncrementHelpVersion -HelpVersionString $OldHelpVersion - $MdContent = Get-Content -raw $LandingPagePath - $MdContent = $MdContent.Replace($OldHelpVersion,$HelpVersion) - Set-Content -path $LandingPagePath -value $MdContent - } - else - { - $HelpVersion = $OldHelpVersion - } - - #Create HelpInfo File - - #Testing the destination directories, creating if none exists. - if(-not (Test-Path $OutputFolder)) - { - Write-Verbose -Message ($LocalizedData.FolderNotFoundCreating -f $OutputFolder) - New-Item -ItemType Directory -Path $OutputFolder | Out-Null - } - - Write-Verbose -Message ($LocalizedData.CabFileInfo -f $ModuleName, $Guid, $Locale) - - #Building the cabinet file name. - $cabName = ("{0}_{1}_{2}_HelpContent.cab" -f $ModuleName,$Guid,$Locale) - $zipName = ("{0}_{1}_{2}_HelpContent.zip" -f $ModuleName,$Guid,$Locale) - $zipPath = (Join-Path $OutputFolder $zipName) - - #Setting Cab Directives, make a cab is turned on, compression is turned on - Write-Verbose -Message ($LocalizedData.CreatingCabFileDirectives) - $DirectiveFile = "dir.dff" - New-Item -ItemType File -Name $DirectiveFile -Force | Out-Null - Add-Content $DirectiveFile ".Set Cabinet=on" - Add-Content $DirectiveFile ".Set Compress=on" - Add-Content $DirectiveFile ".Set MaxDiskSize=CDROM" - - #Creates an entry in the cab directive file for each file in the source directory (uses FullName to get fuly qualified file path and name) - foreach($file in $ValidHelpFiles) - { - Add-Content $DirectiveFile ("'" + ($file).FullName +"'" ) - Compress-Archive -DestinationPath $zipPath -Path $file.FullName -Update - } - - #Making Cab - Write-Verbose -Message ($LocalizedData.CreatingCabFile) - MakeCab.exe /f $DirectiveFile | Out-Null - - #Naming CabFile - Write-Verbose -Message ($LocalizedData.MovingCabFile -f $OutputFolder) - Copy-Item "disk1/1.cab" (Join-Path $OutputFolder $cabName) - - #Remove ExtraFiles created by the cabbing process - Write-Verbose -Message ($LocalizedData.RemovingExtraCabFileContents) - Remove-Item "setup.inf" -ErrorAction SilentlyContinue - Remove-Item "setup.rpt" -ErrorAction SilentlyContinue - Remove-Item $DirectiveFile -ErrorAction SilentlyContinue - Remove-Item -Path "disk1" -Recurse -ErrorAction SilentlyContinue - - #Create the HelpInfo Xml - MakeHelpInfoXml -ModuleName $ModuleName -GUID $Guid -HelpCulture $Locale -HelpVersion $HelpVersion -URI $FwLink -OutputFolder $OutputFolder - - if($AdditionalLocale) - { - $allLocales = $AdditionalLocale -split ',' - - foreach($loc in $allLocales) - { - #Create the HelpInfo Xml for each locale - $locVersion = $Metadata["$loc Version"] - - if([String]::IsNullOrEmpty($locVersion)) - { - Write-Warning -Message ($LocalizedData.VersionNotFoundForLocale -f $loc) - } - else - { - MakeHelpInfoXml -ModuleName $ModuleName -GUID $Guid -HelpCulture $loc -HelpVersion $locVersion -URI $FwLink -OutputFolder $OutputFolder - } - } - } - } -} - -#endregion - -#region Implementation -# IIIIIIIIII lllllll tttt tttt iiii -# I::::::::I l:::::l ttt:::t ttt:::t i::::i -# I::::::::I l:::::l t:::::t t:::::t iiii -# II::::::II l:::::l t:::::t t:::::t -# I::::I mmmmmmm mmmmmmm ppppp ppppppppp l::::l eeeeeeeeeeee mmmmmmm mmmmmmm eeeeeeeeeeee nnnn nnnnnnnn ttttttt:::::ttttttt aaaaaaaaaaaaa ttttttt:::::ttttttt iiiiiii ooooooooooo nnnn nnnnnnnn -# I::::I mm:::::::m m:::::::mm p::::ppp:::::::::p l::::l ee::::::::::::ee mm:::::::m m:::::::mm ee::::::::::::ee n:::nn::::::::nn t:::::::::::::::::t a::::::::::::a t:::::::::::::::::t i:::::i oo:::::::::::oo n:::nn::::::::nn -# I::::I m::::::::::mm::::::::::mp:::::::::::::::::p l::::l e::::::eeeee:::::eem::::::::::mm::::::::::m e::::::eeeee:::::een::::::::::::::nn t:::::::::::::::::t aaaaaaaaa:::::at:::::::::::::::::t i::::i o:::::::::::::::on::::::::::::::nn -# I::::I m::::::::::::::::::::::mpp::::::ppppp::::::p l::::l e::::::e e:::::em::::::::::::::::::::::me::::::e e:::::enn:::::::::::::::ntttttt:::::::tttttt a::::atttttt:::::::tttttt i::::i o:::::ooooo:::::onn:::::::::::::::n -# I::::I m:::::mmm::::::mmm:::::m p:::::p p:::::p l::::l e:::::::eeeee::::::em:::::mmm::::::mmm:::::me:::::::eeeee::::::e n:::::nnnn:::::n t:::::t aaaaaaa:::::a t:::::t i::::i o::::o o::::o n:::::nnnn:::::n -# I::::I m::::m m::::m m::::m p:::::p p:::::p l::::l e:::::::::::::::::e m::::m m::::m m::::me:::::::::::::::::e n::::n n::::n t:::::t aa::::::::::::a t:::::t i::::i o::::o o::::o n::::n n::::n -# I::::I m::::m m::::m m::::m p:::::p p:::::p l::::l e::::::eeeeeeeeeee m::::m m::::m m::::me::::::eeeeeeeeeee n::::n n::::n t:::::t a::::aaaa::::::a t:::::t i::::i o::::o o::::o n::::n n::::n -# I::::I m::::m m::::m m::::m p:::::p p::::::p l::::l e:::::::e m::::m m::::m m::::me:::::::e n::::n n::::n t:::::t tttttta::::a a:::::a t:::::t tttttt i::::i o::::o o::::o n::::n n::::n -# II::::::IIm::::m m::::m m::::m p:::::ppppp:::::::pl::::::le::::::::e m::::m m::::m m::::me::::::::e n::::n n::::n t::::::tttt:::::ta::::a a:::::a t::::::tttt:::::ti::::::io:::::ooooo:::::o n::::n n::::n -# I::::::::Im::::m m::::m m::::m p::::::::::::::::p l::::::l e::::::::eeeeeeee m::::m m::::m m::::m e::::::::eeeeeeee n::::n n::::n tt::::::::::::::ta:::::aaaa::::::a tt::::::::::::::ti::::::io:::::::::::::::o n::::n n::::n -# I::::::::Im::::m m::::m m::::m p::::::::::::::pp l::::::l ee:::::::::::::e m::::m m::::m m::::m ee:::::::::::::e n::::n n::::n tt:::::::::::tt a::::::::::aa:::a tt:::::::::::tti::::::i oo:::::::::::oo n::::n n::::n -# IIIIIIIIIImmmmmm mmmmmm mmmmmm p::::::pppppppp llllllll eeeeeeeeeeeeee mmmmmm mmmmmm mmmmmm eeeeeeeeeeeeee nnnnnn nnnnnn ttttttttttt aaaaaaaaaa aaaa ttttttttttt iiiiiiii ooooooooooo nnnnnn nnnnnn -# p:::::p -# p:::::p -# p:::::::p -# p:::::::p -# p:::::::p -# ppppppppp - -# parse out the list "applicable" tags from yaml header -function GetApplicableList -{ - param( - [Parameter(Mandatory=$true)] - $Path - ) - - $h = Get-MarkdownMetadata -Path $Path - if ($h -and $h[$script:APPLICABLE_YAML_HEADER]) { - return $h[$script:APPLICABLE_YAML_HEADER].Split(',').Trim() - } -} - -function SortParamsAlphabetically -{ - param( - [Parameter(Mandatory=$true)] - $MamlCommandObject - ) - - # sort parameters alphabetically with minor exceptions - # https://github.com/PowerShell/platyPS/issues/142 - $confirm = $MamlCommandObject.Parameters | Where-Object { $_.Name -eq 'Confirm' } - $whatif = $MamlCommandObject.Parameters | Where-Object { $_.Name -eq 'WhatIf' } - $includeTotalCount = $MamlCommandObject.Parameters | Where-Object { $_.Name -eq 'IncludeTotalCount' } - $skip = $MamlCommandObject.Parameters | Where-Object { $_.Name -eq 'Skip' } - $first = $MamlCommandObject.Parameters | Where-Object { $_.Name -eq 'First' } - - if ($confirm) - { - $MamlCommandObject.Parameters.Remove($confirm) > $null - } - - if ($whatif) - { - $MamlCommandObject.Parameters.Remove($whatif) > $null - } - - if ($includeTotalCount) - { - $MamlCommandObject.Parameters.Remove($includeTotalCount) > $null - } - - if ($skip) - { - $MamlCommandObject.Parameters.Remove($skip) > $null - } - - if ($first) - { - $MamlCommandObject.Parameters.Remove($first) > $null - } - - $sortedParams = $MamlCommandObject.Parameters | Sort-Object -Property Name - $MamlCommandObject.Parameters.Clear() - - $sortedParams | ForEach-Object { - $MamlCommandObject.Parameters.Add($_) - } - - if ($confirm) - { - $MamlCommandObject.Parameters.Add($confirm) - } - - if ($whatif) - { - $MamlCommandObject.Parameters.Add($whatif) - } - - if ($includeTotalCount) - { - $MamlCommandObject.Parameters.Add($includeTotalCount) - } - - if ($skip) - { - $MamlCommandObject.Parameters.Add($skip) - } - - if ($first) - { - $MamlCommandObject.Parameters.Add($first) - } -} - -# If LogPath not provided, use -Verbose output for logs -function GetInfoCallback -{ - param( - [string]$LogPath, - [switch]$Append - ) - - if ($LogPath) - { - if (-not (Test-Path $LogPath -PathType Leaf)) - { - $containerFolder = Split-Path $LogPath - if ($containerFolder) - { - # this if is for $LogPath -eq foo.log case - New-Item -Type Directory $containerFolder -ErrorAction SilentlyContinue > $null - } - - if (-not $Append) - { - # wipe the file, so it can be reused - Set-Content -Path $LogPath -value '' -Encoding UTF8 - } - } - - $infoCallback = { - param([string]$message) - Add-Content -Path $LogPath -value $message -Encoding UTF8 - } - } - else - { - $infoCallback = { - param([string]$message) - Write-Verbose $message - } - } - return $infoCallback -} - -function GetWarningCallback -{ - $warningCallback = { - param([string]$message) - Write-Warning $message - } - - return $warningCallback -} - -function GetAboutTopicsFromPath -{ - [CmdletBinding()] - param( - [Parameter(Mandatory=$true)] - [string[]]$Path, - [string[]]$MarkDownFilesAlreadyFound - ) - - function ConfirmAboutBySecondHeaderText - { - param( - [string]$AboutFilePath - ) - - $MdContent = Get-Content -raw $AboutFilePath - $MdParser = new-object -TypeName 'Markdown.MAML.Parser.MarkdownParser' ` - -ArgumentList { param([int]$current, [int]$all) - Write-Progress -Activity $LocalizedData.ParsingMarkdown -status $LocalizedData.Progress -percentcomplete ($current/$all*100)} - $MdObject = $MdParser.ParseString($MdContent) - - if($MdObject.Children[1].text.length -gt 5) - { - if($MdObject.Children[1].text.substring(0,5).ToUpper() -eq "ABOUT") - { - return $true - } - } - - return $false - } - - $AboutMarkDownFiles = @() - - if ($Path) { - $Path | ForEach-Object { - if (Test-Path -PathType Leaf $_) - { - if(ConfirmAboutBySecondHeaderText($_)) - { - $AboutMarkdownFiles += Get-ChildItem $_ - } - } - elseif (Test-Path -PathType Container $_) - { - if($MarkDownFilesAlreadyFound) - { - $AboutMarkdownFiles += Get-ChildItem $_ -Filter '*.md' | Where-Object {($_.FullName -notin $MarkDownFilesAlreadyFound) -and (ConfirmAboutBySecondHeaderText($_.FullName))} - } - else - { - $AboutMarkdownFiles += Get-ChildItem $_ -Filter '*.md' | Where-Object {ConfirmAboutBySecondHeaderText($_.FullName)} - } - } - else - { - Write-Error -Message ($LocalizedData.AboutFileNotFound -f $_) - } - } - } - - - - return $AboutMarkDownFiles -} - -function GetMarkdownFilesFromPath -{ - [CmdletBinding()] - param( - [Parameter(Mandatory=$true)] - [SupportsWildcards()] - [string[]]$Path, - - [switch]$IncludeModulePage - ) - - if ($IncludeModulePage) - { - $filter = '*.md' - } - else - { - $filter = '*-*.md' - } - - $aboutFilePrefixPattern = 'about_*' - - - $MarkdownFiles = @() - if ($Path) { - $Path | ForEach-Object { - if (Test-Path -PathType Leaf $_) - { - if ((Split-Path -Leaf $_) -notlike $aboutFilePrefixPattern) - { - $MarkdownFiles += Get-ChildItem $_ - } - } - elseif (Test-Path -PathType Container $_) - { - $MarkdownFiles += Get-ChildItem $_ -Filter $filter | Where-Object {$_.BaseName -notlike $aboutFilePrefixPattern} - } - else - { - Write-Error -Message ($LocalizedData.PathNotFound -f $_) - } - } - } - - return $MarkdownFiles -} - -function GetParserMode -{ - param( - [switch]$PreserveFormatting - ) - - if ($PreserveFormatting) - { - return [Markdown.MAML.Parser.ParserMode]::FormattingPreserve - } - else - { - return [Markdown.MAML.Parser.ParserMode]::Full - } -} - -function GetMamlModelImpl -{ - param( - [Parameter(Mandatory=$true)] - [string[]]$markdownFiles, - [Parameter(Mandatory=$true)] - [System.Text.Encoding]$Encoding, - [switch]$ForAnotherMarkdown, - [String[]]$ApplicableTag - ) - - if ($ForAnotherMarkdown -and $ApplicableTag) { - throw $LocalizedData.ForAnotherMarkdownAndApplicableTag - } - - # we need to pass it into .NET IEnumerable<MamlCommand> API - $res = New-Object 'System.Collections.Generic.List[Markdown.MAML.Model.MAML.MamlCommand]' - - $markdownFiles | ForEach-Object { - $mdText = MyGetContent $_ -Encoding $Encoding - $schema = GetSchemaVersion $mdText - $p = NewMarkdownParser - $t = NewModelTransformer -schema $schema $ApplicableTag - - $parseMode = GetParserMode -PreserveFormatting:$ForAnotherMarkdown - $model = $p.ParseString($mdText, $parseMode, $_) - Write-Progress -Activity $LocalizedData.ParsingMarkdown -Completed - $maml = $t.NodeModelToMamlModel($model) - - # flatten - $maml | ForEach-Object { - if (-not $ForAnotherMarkdown) - { - # we are preparing model to be transformed in MAML, need to embeed online version url - SetOnlineVersionUrlLink -MamlCommandObject $_ -OnlineVersionUrl (GetOnlineVersion $mdText) - } - - $res.Add($_) - } - } - - return @(,$res) -} - -function NewMarkdownParser -{ - $warningCallback = GetWarningCallback - $progressCallback = { - param([int]$current, [int]$all) - Write-Progress -Activity $LocalizedData.ParsingMarkdown -status $LocalizedData.Progress -percentcomplete ($current/$all*100) - } - return new-object -TypeName 'Markdown.MAML.Parser.MarkdownParser' -ArgumentList ($progressCallback, $warningCallback) -} - -function NewModelTransformer -{ - param( - [ValidateSet('1.0.0', '2.0.0')] - [string]$schema, - [string[]]$ApplicableTag - ) - - if ($schema -eq '1.0.0') - { - throw $LocalizedData.PlatyPS100SchemaDeprecated - } - elseif ($schema -eq '2.0.0') - { - $infoCallback = { - param([string]$message) - Write-Verbose $message - } - $warningCallback = GetWarningCallback - return new-object -TypeName 'Markdown.MAML.Transformer.ModelTransformerVersion2' -ArgumentList ($infoCallback, $warningCallback, $ApplicableTag) - } -} - -function GetSchemaVersion -{ - param( - [string]$markdown - ) - - $metadata = Get-MarkdownMetadata -markdown $markdown - if ($metadata) - { - $schema = $metadata[$script:SCHEMA_VERSION_YAML_HEADER] - } - - if (-not $schema) - { - # either there is no metadata, or schema version is not specified. - # assume 2.0.0 - $schema = '2.0.0' - } - - return $schema -} - -function GetOnlineVersion -{ - param( - [string]$markdown - ) - - $metadata = Get-MarkdownMetadata -markdown $markdown - $onlineVersionUrl = $null - if ($metadata) - { - $onlineVersionUrl = $metadata[$script:ONLINE_VERSION_YAML_HEADER] - } - - return $onlineVersionUrl -} - -function SetOnlineVersionUrlLink -{ - param( - [Parameter(Mandatory=$true)] - [Markdown.MAML.Model.MAML.MamlCommand]$MamlCommandObject, - - [string]$OnlineVersionUrl = $null - ) - - # Online Version URL - $currentFirstLink = $MamlCommandObject.Links | Select-Object -First 1 - - if ($OnlineVersionUrl -and ((-not $currentFirstLink) -or ($currentFirstLink.LinkUri -ne $OnlineVersionUrl))) { - $mamlLink = New-Object -TypeName Markdown.MAML.Model.MAML.MamlLink - $mamlLink.LinkName = $script:MAML_ONLINE_LINK_DEFAULT_MONIKER - $mamlLink.LinkUri = $OnlineVersionUrl - - # Insert link at the beginning - $MamlCommandObject.Links.Insert(0, $mamlLink) - } -} - -function MakeHelpInfoXml -{ - Param( - [Parameter(mandatory=$true)] - [string] - $ModuleName, - [Parameter(mandatory=$true)] - [string] - $GUID, - [Parameter(mandatory=$true)] - [string] - $HelpCulture, - [Parameter(mandatory=$true)] - [string] - $HelpVersion, - [Parameter(mandatory=$true)] - [string] - $URI, - [Parameter(mandatory=$true)] - [string] - $OutputFolder - - - ) - - $HelpInfoFileNme = $ModuleName + "_" + $GUID + "_HelpInfo.xml" - $OutputFullPath = Join-Path $OutputFolder $HelpInfoFileNme - - if(Test-Path $OutputFullPath -PathType Leaf) - { - [xml] $HelpInfoContent = Get-Content $OutputFullPath - } - - #Create the base XML object for the Helpinfo.xml file. - $xml = new-object xml - - $ns = "http://schemas.microsoft.com/powershell/help/2010/05" - $declaration = $xml.CreateXmlDeclaration("1.0","utf-8",$null) - - $rootNode = $xml.CreateElement("HelpInfo",$ns) - $xml.InsertBefore($declaration,$xml.DocumentElement) - $xml.AppendChild($rootNode) - - $HelpContentUriNode = $xml.CreateElement("HelpContentURI",$ns) - $HelpContentUriNode.InnerText = $URI - $xml["HelpInfo"].AppendChild($HelpContentUriNode) - - $HelpSupportedCulturesNode = $xml.CreateElement("SupportedUICultures",$ns) - $xml["HelpInfo"].AppendChild($HelpSupportedCulturesNode) - - - #If no previous help file - if(-not $HelpInfoContent) - { - $HelpUICultureNode = $xml.CreateElement("UICulture",$ns) - $xml["HelpInfo"]["SupportedUICultures"].AppendChild($HelpUICultureNode) - - $HelpUICultureNameNode = $xml.CreateElement("UICultureName",$ns) - $HelpUICultureNameNode.InnerText = $HelpCulture - $xml["HelpInfo"]["SupportedUICultures"]["UICulture"].AppendChild($HelpUICultureNameNode) - - $HelpUICultureVersionNode = $xml.CreateElement("UICultureVersion",$ns) - $HelpUICultureVersionNode.InnerText = $HelpVersion - $xml["HelpInfo"]["SupportedUICultures"]["UICulture"].AppendChild($HelpUICultureVersionNode) - - [xml] $HelpInfoContent = $xml - - } - else - { - #Get old culture info - $ExistingCultures = @{} - foreach($Culture in $HelpInfoContent.HelpInfo.SupportedUICultures.UICulture) - { - $ExistingCultures.Add($Culture.UICultureName, $Culture.UICultureVersion) - } - - #If culture exists update version, if not, add culture and version - if(-not ($HelpCulture -in $ExistingCultures.Keys)) - { - $ExistingCultures.Add($HelpCulture,$HelpVersion) - } - else - { - $ExistingCultures[$HelpCulture] = $HelpVersion - } - - $cultureNames = @() - $cultureNames += $ExistingCultures.GetEnumerator() - - #write out cultures to XML - for($i=0;$i -lt $ExistingCultures.Count; $i++) - { - $HelpUICultureNode = $xml.CreateElement("UICulture",$ns) - - - $HelpUICultureNameNode = $xml.CreateElement("UICultureName",$ns) - $HelpUICultureNameNode.InnerText = $cultureNames[$i].Name - $HelpUICultureNode.AppendChild($HelpUICultureNameNode) - - $HelpUICultureVersionNode = $xml.CreateElement("UICultureVersion",$ns) - $HelpUICultureVersionNode.InnerText = $cultureNames[$i].Value - $HelpUICultureNode.AppendChild($HelpUICultureVersionNode) - - $xml["HelpInfo"]["SupportedUICultures"].AppendChild($HelpUICultureNode) - } - - [xml] $HelpInfoContent = $xml - } - - #Commit Help - if(!(Test-Path $OutputFullPath)) - { - New-Item -Path $OutputFolder -ItemType File -Name $HelpInfoFileNme - - } - - $HelpInfoContent.Save((Get-ChildItem $OutputFullPath).FullName) - -} - - -function GetHelpFileName -{ - param( - [System.Management.Automation.CommandInfo]$CommandInfo - ) - - if ($CommandInfo) - { - if ($CommandInfo.HelpFile) - { - if ([System.IO.Path]::IsPathRooted($CommandInfo.HelpFile)) - { - return (Split-Path -Leaf $CommandInfo.HelpFile) - } - else - { - return $CommandInfo.HelpFile - } - } - # only run module evaluations if the input command isn't a script - if ($CommandInfo.CommandType -ne "ExternalScript") - { - # overwise, lets guess it - $module = @($CommandInfo.Module) + ($CommandInfo.Module.NestedModules) | - Where-Object {$_.ModuleType -ne 'Manifest'} | - Where-Object {$_.ExportedCommands.Keys -contains $CommandInfo.Name} - - if (-not $module) - { - Write-Warning -Message ($LocalizedData.ModuleNotFoundFromCommand -f '[GetHelpFileName]', $CommandInfo.Name) - return - } - - if ($module.Count -gt 1) - { - Write-Warning -Message ($LocalizedData.MultipleModulesFoundFromCommand -f '[GetHelpFileName]', $CommandInfo.Name) - $module = $module | Select-Object -First 1 - } - - if (Test-Path $module.Path -Type Leaf) - { - # for regular modules, we can deduct the filename from the module path file - $moduleItem = Get-Item -Path $module.Path - if ($moduleItem.Extension -eq '.psm1') { - $fileName = $moduleItem.BaseName - } else { - $fileName = $moduleItem.Name - } - } - else - { - # if it's something like Dynamic module, - # we guess the desired help file name based on the module name - $fileName = $module.Name - } - } - - return "$fileName-help.xml" - } -} - -function MySetContent -{ - [OutputType([System.IO.FileInfo])] - param( - [Parameter(Mandatory=$true)] - [string]$Path, - [Parameter(Mandatory=$true)] - [string]$value, - [Parameter(Mandatory=$true)] - [System.Text.Encoding]$Encoding, - [switch]$Force - ) - - if (Test-Path $Path) - { - if (Test-Path $Path -PathType Container) - { - Write-Error -Message ($LocalizedData.CannotWriteFileDirectoryExists -f $Path) - return - } - - if ((MyGetContent -Path $Path -Encoding $Encoding) -eq $value) - { - Write-Verbose "Not writing to $Path, because content is not changing." - return (Get-ChildItem $Path) - } - - if (-not $Force) - { - Write-Error -Message ($LocalizedData.CannotWriteFileWithoutForce -f $Path) - return - } - } - else - { - $dir = Split-Path $Path - if ($dir) - { - New-Item -Type Directory $dir -ErrorAction SilentlyContinue > $null - } - } - - Write-Verbose -Message ($LocalizedData.WritingWithEncoding -f $Path, $Encoding.EncodingName) - # just to create a file - Set-Content -Path $Path -Value '' - $resolvedPath = (Get-ChildItem $Path).FullName - [System.IO.File]::WriteAllText($resolvedPath, $value, $Encoding) - return (Get-ChildItem $Path) -} - -function MyGetContent -{ - [OutputType([System.String])] - param( - [Parameter(Mandatory=$true)] - [string]$Path, - [Parameter(Mandatory=$true)] - [System.Text.Encoding]$Encoding - ) - - if (-not(Test-Path $Path)) - { - throw $LocalizedData.FileNotFound - return - } - else - { - if (Test-Path $Path -PathType Container) - { - throw $LocalizedData.PathIsNotFile - return - } - } - - Write-Verbose -Message ($LocalizedData.ReadingWithEncoding -f $Path, $Encoding.EncodingName) - $resolvedPath = (Get-ChildItem $Path).FullName - return [System.IO.File]::ReadAllText($resolvedPath, $Encoding) -} - -function NewModuleLandingPage -{ - Param( - [Parameter(mandatory=$true)] - [string] - $Path, - [Parameter(mandatory=$true)] - [string] - $ModuleName, - [Parameter(mandatory=$true,ParameterSetName="NewLandingPage")] - [string] - $ModuleGuid, - [Parameter(mandatory=$true,ParameterSetName="NewLandingPage")] - [string[]] - $CmdletNames, - [Parameter(mandatory=$true,ParameterSetName="NewLandingPage")] - [string] - $Locale, - [Parameter(mandatory=$true,ParameterSetName="NewLandingPage")] - [string] - $Version, - [Parameter(mandatory=$true,ParameterSetName="NewLandingPage")] - [string] - $FwLink, - [Parameter(ParameterSetName="UpdateLandingPage")] - [switch] - $RefreshModulePage, - [string]$ModulePagePath, - [Parameter(mandatory=$true,ParameterSetName="UpdateLandingPage")] - [System.Collections.Generic.List[Markdown.MAML.Model.MAML.MamlCommand]] - $Module, - [Parameter(mandatory=$true)] - [System.Text.Encoding]$Encoding = $script:UTF8_NO_BOM, - [switch]$Force - ) - - begin - { - if ($ModulePagePath) { - $LandingPagePath = $ModulePagePath - } else { - $LandingPageName = $ModuleName + ".md" - $LandingPagePath = Join-Path $Path $LandingPageName - } - } - - process - { - $Description = $LocalizedData.Description - - if($RefreshModulePage) - { - if(Test-Path $LandingPagePath) - { - $OldLandingPageContent = Get-Content -Raw $LandingPagePath - $OldMetaData = Get-MarkdownMetadata -Markdown $OldLandingPageContent - $ModuleGuid = $OldMetaData["Module Guid"] - $FwLink = $OldMetaData["Download Help Link"] - $Version = $OldMetaData["Help Version"] - $Locale = $OldMetaData["Locale"] - - $p = NewMarkdownParser - $model = $p.ParseString($OldLandingPageContent) - $index = $model.Children.IndexOf(($model.Children | Where-Object {$_.Text -eq "Description"})) - $i = 1 - $stillParagraph = $true - $Description = "" - while($stillParagraph -eq $true) - { - $Description += $model.Children[$index + $i].spans.text - $i++ - - if($model.Children[$i].NodeType -eq "Heading") - { - $stillParagraph = $false - } - } - } - else - { - $ModuleGuid = $LocalizedData.ModuleGuid - $FwLink = $LocalizedData.FwLink - $Version = $LocalizedData.Version - $Locale = $LocalizedData.Locale - $Description = $LocalizedData.Description - } - } - - $Content = "---`r`nModule Name: $ModuleName`r`nModule Guid: $ModuleGuid`r`nDownload Help Link: $FwLink`r`n" - $Content += "Help Version: $Version`r`nLocale: $Locale`r`n" - $Content += "---`r`n`r`n" - $Content += "# $ModuleName Module`r`n## Description`r`n" - $Content += "$Description`r`n`r`n## $ModuleName Cmdlets`r`n" - - if($RefreshModulePage) - { - $Module | ForEach-Object { - $command = $_ - if(-not $command.Synopsis) - { - $Content += "### [" + $command.Name + "](" + $command.Name + ".md)`r`n" + $LocalizedData.Description + "`r`n`r`n" - } - else - { - $Content += "### [" + $command.Name + "](" + $command.Name + ".md)`r`n" + $command.Synopsis + "`r`n`r`n" - } - } - } - else - { - $CmdletNames | ForEach-Object { - $Content += "### [" + $_ + "](" + $_ + ".md)`r`n" + $LocalizedData.Description + "`r`n`r`n" - } - } - - MySetContent -Path $LandingPagePath -value $Content -Encoding $Encoding -Force:$Force # yeild - } - -} - -function ConvertMamlModelToMarkdown -{ - param( - [ValidateNotNullOrEmpty()] - [Parameter(Mandatory=$true)] - [Markdown.MAML.Model.MAML.MamlCommand]$mamlCommand, - - [hashtable]$metadata, - - [switch]$NoMetadata, - - [switch]$PreserveFormatting - ) - - begin - { - $parseMode = GetParserMode -PreserveFormatting:$PreserveFormatting - $r = New-Object Markdown.MAML.Renderer.MarkdownV2Renderer -ArgumentList $parseMode - $count = 0 - } - - process - { - if (($count++) -eq 0 -and (-not $NoMetadata)) - { - return $r.MamlModelToString($mamlCommand, $metadata) - } - else - { - return $r.MamlModelToString($mamlCommand, $true) # skip version header - } - } -} - -function GetCommands -{ - param( - [Parameter(Mandatory=$true)] - [string]$Module, - # return names, instead of objects - [switch]$AsNames, - # use Session for remoting support - [System.Management.Automation.Runspaces.PSSession]$Session - ) - - process { - # Get-Module doesn't know about Microsoft.PowerShell.Core, so we don't use (Get-Module).ExportedCommands - - # We use: & (dummy module) {...} syntax to workaround - # the case `GetMamlObject -Module platyPS` - # because in this case, we are in the module context and Get-Command returns all commands, - # not only exported ones. - $commands = & (New-Module {}) ([scriptblock]::Create("Get-Command -Module '$Module'")) | - Where-Object {$_.CommandType -ne 'Alias'} # we don't want aliases in the markdown output for a module - - if ($AsNames) - { - $commands.Name - } - else - { - if ($Session) { - $commands.Name | ForEach-Object { - # yeild - MyGetCommand -Cmdlet $_ -Session $Session - } - } else { - $commands - } - } - } -} - -<# - Get a compact string representation from TypeInfo or TypeInfo-like object - - The typeObjectHash api is provided for the remoting support. - We use two different parameter sets ensure the tupe of -TypeObject -#> -function GetTypeString -{ - param( - [Parameter(ValueFromPipeline=$true, ParameterSetName='typeObject')] - [System.Reflection.TypeInfo] - $TypeObject, - - [Parameter(ValueFromPipeline=$true, ParameterSetName='typeObjectHash')] - [PsObject] - $TypeObjectHash - ) - - if ($TypeObject) { - $TypeObjectHash = $TypeObject - } - - # special case for nullable value types - if ($TypeObjectHash.Name -eq 'Nullable`1') - { - return $TypeObjectHash.GenericTypeArguments.Name - } - - if ($TypeObjectHash.IsGenericType) - { - # keep information about generic parameters - return $TypeObjectHash.ToString() - } - - return $TypeObjectHash.Name -} - -<# - You cannot just write 0..($n-1) because if $n == 0 you are screwed. - Hence this helper. -#> -function GetRange -{ - Param( - [CmdletBinding()] - [parameter(mandatory=$true)] - [int]$n - ) - if ($n -lt 0) { - throw $LocalizedData.RangeIsLessThanZero -f $n - } - if ($n -eq 0) { - return - } - 0..($n - 1) -} - -<# - This function proxies Get-Command call. - - In case of the Remote module, we need to jump thru some hoops - to get the actual Command object with proper fields. - Remoting doesn't properly serialize command objects, so we need to be creative - while extracting all the required metadata from the remote session - See https://github.com/PowerShell/platyPS/issues/338 for historical context. -#> -function MyGetCommand -{ - Param( - [CmdletBinding()] - [parameter(mandatory=$true, parametersetname="Cmdlet")] - [string] $Cmdlet, - [System.Management.Automation.Runspaces.PSSession]$Session - ) - # if there is no remoting, just proxy to Get-Command - if (-not $Session) { - return Get-Command $Cmdlet - } - - # Here is the structure that we use in ConvertPsObjectsToMamlModel - # we fill it up from the remote with some workarounds - # - # $Command.CommandType - # $Command.Name - # $Command.ModuleName - # $Command.DefaultParameterSet - # $Command.CmdletBinding - # $ParameterSet in $Command.ParameterSets - # $ParameterSet.Name - # $ParameterSet.IsDefault - # $Parameter in $ParameterSet.Parameters - # $Parameter.Name - # $Parameter.IsMandatory - # $Parameter.Aliases - # $Parameter.HelpMessage - # $Parameter.Type - # $Parameter.ParameterType - # $Parameter.ParameterType.Name - # $Parameter.ParameterType.GenericTypeArguments.Name - # $Parameter.ParameterType.IsGenericType - # $Parameter.ParameterType.ToString() - we get that for free from expand - - # expand first layer of properties - function expand([string]$property) { - Invoke-Command -Session $Session -ScriptBlock { - Get-Command $using:Cmdlet | - Select-Object -ExpandProperty $using:property - } - } - - # expand second layer of properties on the selected item - function expand2([string]$property1, [int]$num, [string]$property2) { - Invoke-Command -Session $Session -ScriptBlock { - Get-Command $using:Cmdlet | - Select-Object -ExpandProperty $using:property1 | - Select-Object -Index $using:num -Wait | - Select-Object -ExpandProperty $using:property2 - } - } - - # expand second and 3rd layer of properties on the selected item - function expand3( - [string]$property1, - [int]$num, - [string]$property2, - [string]$property3 - ) { - Invoke-Command -Session $Session -ScriptBlock { - Get-Command $using:Cmdlet | - Select-Object -ExpandProperty $using:property1 | - Select-Object -Index $using:num -Wait | - Select-Object -ExpandProperty $using:property2 | - Select-Object -ExpandProperty $using:property3 - } - } - - function local([string]$property) { - Get-Command $Cmdlet | select-object -ExpandProperty $property - } - - # helper function to fill up the parameters metadata - function getParams([int]$num) { - # this call we need to fill-up ParameterSets.Parameters.ParameterType with metadata - $parameterType = expand3 'ParameterSets' $num 'Parameters' 'ParameterType' - # this call we need to fill-up ParameterSets.Parameters with metadata - $parameters = expand2 'ParameterSets' $num 'Parameters' - if ($parameters.Length -ne $parameterType.Length) { - Write-Error -Message ($LocalizedData.MetadataDoesNotMatchLength -f $Cmdlet) - } - - foreach ($i in (GetRange $parameters.Length)) { - $typeObjectHash = New-Object -TypeName pscustomobject -Property @{ - Name = $parameterType[$i].Name - IsGenericType = $parameterType[$i].IsGenericType - # almost .ParameterType.GenericTypeArguments.Name - # TODO: doesn't it worth another round-trip to make it more accurate - # and query for the Name? - GenericTypeArguments = @{ Name = $parameterType[$i].GenericTypeArguments } - } - Add-Member -Type NoteProperty -InputObject $parameters[$i] -Name 'ParameterTypeName' -Value (GetTypeString -TypeObjectHash $typeObjectHash) - } - return $parameters - } - - # we cannot use the nested properties from this $remote command. - # ps remoting doesn't serialize all of them properly. - # but we can use the top-level onces - $remote = Invoke-Command -Session $Session { Get-Command $using:Cmdlet } - - $psets = expand 'ParameterSets' - $psetsArray = @() - foreach ($i in (GetRange ($psets | measure-object).Count)) { - $parameters = getParams $i - $psetsArray += @(New-Object -TypeName pscustomobject -Property @{ - Name = $psets[$i].Name - IsDefault = $psets[$i].IsDefault - Parameters = $parameters - }) - } - - $commandHash = @{ - Name = $Cmdlet - CommandType = $remote.CommandType - DefaultParameterSet = $remote.DefaultParameterSet - CmdletBinding = $remote.CmdletBinding - # for office we cannot get the module name from the remote, grab the local one instead - ModuleName = local 'ModuleName' - ParameterSets = $psetsArray - } - - return New-Object -TypeName pscustomobject -Property $commandHash -} - -<# - This function prepares help and command object (possibly do mock) - and passes it to ConvertPsObjectsToMamlModel, then return results -#> -function GetMamlObject -{ - Param( - [CmdletBinding()] - [parameter(mandatory=$true, parametersetname="Cmdlet")] - [string] $Cmdlet, - [parameter(mandatory=$true, parametersetname="Module")] - [string] $Module, - [parameter(mandatory=$true, parametersetname="Maml")] - [string] $MamlFile, - [parameter(parametersetname="Maml")] - [switch] $ConvertNotesToList, - [parameter(parametersetname="Maml")] - [switch] $ConvertDoubleDashLists, - [switch] $UseFullTypeName, - [parameter(parametersetname="Cmdlet")] - [parameter(parametersetname="Module")] - [System.Management.Automation.Runspaces.PSSession]$Session, - [switch]$ExcludeDontShow - ) - - function CommandHasAutogeneratedSynopsis - { - param([object]$help) - - return (Get-Command $help.Name -Syntax) -eq ($help.Synopsis) - } - - if($Cmdlet) - { - Write-Verbose -Message ($LocalizedData.Processing -f $Cmdlet) - $Help = Get-Help $Cmdlet - $Command = MyGetCommand -Session $Session -Cmdlet $Cmdlet - return ConvertPsObjectsToMamlModel -Command $Command -Help $Help -UsePlaceholderForSynopsis:(CommandHasAutogeneratedSynopsis $Help) -UseFullTypeName:$UseFullTypeName -ExcludeDontShow:$ExcludeDontShow - } - elseif ($Module) - { - Write-Verbose -Message ($LocalizedData.Processing -f $Module) - - # GetCommands is slow over remoting, piping here is important for good UX - GetCommands $Module -Session $Session | ForEach-Object { - $Command = $_ - Write-Verbose -Message ("`t" + ($LocalizedData.Processing -f $Command.Name)) - $Help = Get-Help $Command.Name - # yield - ConvertPsObjectsToMamlModel -Command $Command -Help $Help -UsePlaceholderForSynopsis:(CommandHasAutogeneratedSynopsis $Help) -UseFullTypeName:$UseFullTypeName -ExcludeDontShow:$ExcludeDontShow - } - } - else # Maml - { - $HelpCollection = Get-HelpPreview -Path $MamlFile -ConvertNotesToList:$ConvertNotesToList -ConvertDoubleDashLists:$ConvertDoubleDashLists - - #Provides Name, CommandType, and Empty Module name from MAML generated module in the $command object. - #Otherwise loads the results from Get-Command <Cmdlet> into the $command object - - $HelpCollection | ForEach-Object { - - $Help = $_ - - $Command = [PsObject] @{ - Name = $Help.Name - CommandType = $Help.Category - HelpFile = (Split-Path $MamlFile -Leaf) - } - - # yield - ConvertPsObjectsToMamlModel -Command $Command -Help $Help -UseHelpForParametersMetadata -UseFullTypeName:$UseFullTypeName -ExcludeDontShow:$ExcludeDontShow - } - } -} - -function AddLineBreaksForParagraphs -{ - [CmdletBinding()] - param( - [Parameter(Mandatory=$false, ValueFromPipeline=$true)] - [string]$text - ) - - begin - { - $paragraphs = @() - } - - process - { - $text = $text.Trim() - $paragraphs += $text - } - - end - { - $paragraphs -join "`r`n`r`n" - } -} - -function DescriptionToPara -{ - [CmdletBinding()] - param( - [Parameter(Mandatory=$false, ValueFromPipeline=$true)] - $description - ) - - process - { - # on some old maml modules description uses Tag to store *-bullet-points - # one example of it is Exchange - $description.Tag + "" + $description.Text - } -} - -function IncrementHelpVersion -{ - param( - [string] - $HelpVersionString - ) - process - { - if($HelpVersionString -eq $LocalizedData.HelpVersion) - { - return "1.0.0.0" - } - $lastDigitPosition = $HelpVersionString.LastIndexOf(".") + 1 - $frontDigits = $HelpVersionString.Substring(0,$lastDigitPosition) - $frontDigits += ([int] $HelpVersionString.Substring($lastDigitPosition)) + 1 - return $frontDigits - } -} - -<# - This function converts help and command object (possibly mocked) into a Maml Model -#> -function ConvertPsObjectsToMamlModel -{ - [CmdletBinding()] - [OutputType([Markdown.MAML.Model.MAML.MamlCommand])] - param( - [Parameter(Mandatory=$true)] - [object]$Command, - [Parameter(Mandatory=$true)] - [object]$Help, - [switch]$UseHelpForParametersMetadata, - [switch]$UsePlaceholderForSynopsis, - [switch]$UseFullTypeName, - [switch]$ExcludeDontShow - ) - - function isCommonParameterName - { - param([string]$parameterName, [switch]$Workflow) - - if (@( - 'Verbose', - 'Debug', - 'ErrorAction', - 'WarningAction', - 'InformationAction', - 'ErrorVariable', - 'WarningVariable', - 'InformationVariable', - 'OutVariable', - 'OutBuffer', - 'PipelineVariable' - ) -contains $parameterName) { - return $true - } - - if ($Workflow) - { - return @( - 'PSParameterCollection', - 'PSComputerName', - 'PSCredential', - 'PSConnectionRetryCount', - 'PSConnectionRetryIntervalSec', - 'PSRunningTimeoutSec', - 'PSElapsedTimeoutSec', - 'PSPersist', - 'PSAuthentication', - 'PSAuthenticationLevel', - 'PSApplicationName', - 'PSPort', - 'PSUseSSL', - 'PSConfigurationName', - 'PSConnectionURI', - 'PSAllowRedirection', - 'PSSessionOption', - 'PSCertificateThumbprint', - 'PSPrivateMetadata', - 'AsJob', - 'JobName' - ) -contains $parameterName - } - - return $false - } - - function getPipelineValue($Parameter) - { - if ($Parameter.ValueFromPipeline) - { - if ($Parameter.ValueFromPipelineByPropertyName) - { - return 'True (ByPropertyName, ByValue)' - } - else - { - return 'True (ByValue)' - } - } - else - { - if ($Parameter.ValueFromPipelineByPropertyName) - { - return 'True (ByPropertyName)' - } - else - { - return 'False' - } - } - } - - function normalizeFirstLatter - { - param( - [Parameter(ValueFromPipeline=$true)] - [string]$value - ) - - if ($value -and $value.Length -gt 0) - { - return $value.Substring(0,1).ToUpperInvariant() + $value.substring(1) - } - - return $value - } - - #endregion - - $MamlCommandObject = New-Object -TypeName Markdown.MAML.Model.MAML.MamlCommand - - #region Command Object Values Processing - - $IsWorkflow = $Command.CommandType -eq 'Workflow' - - #Get Name - $MamlCommandObject.Name = $Command.Name - - $MamlCommandObject.ModuleName = $Command.ModuleName - - #region Data not provided by the command object - - #Get Description - #Not provided by the command object. - $MamlCommandObject.Description = New-Object -TypeName Markdown.MAML.Model.Markdown.SectionBody ($LocalizedData.Description) - - #endregion - - #Get Syntax - #region Get the Syntax Parameter Set objects - - function FillUpParameterFromHelp - { - param( - [Parameter(Mandatory=$true)] - [Markdown.MAML.Model.MAML.MamlParameter]$ParameterObject - ) - - $HelpEntry = $Help.parameters.parameter | Where-Object {$_.Name -eq $ParameterObject.Name} - - $ParameterObject.DefaultValue = $HelpEntry.defaultValue | normalizeFirstLatter - $ParameterObject.VariableLength = $HelpEntry.variableLength -eq 'True' - $ParameterObject.Position = $HelpEntry.position | normalizeFirstLatter - if ($HelpEntry.description) - { - if ($HelpEntry.description.text) - { - $ParameterObject.Description = $HelpEntry.description | - DescriptionToPara | - AddLineBreaksForParagraphs - } - else - { - # this case happens, when there is HelpMessage in 'Parameter' attribute, - # but there is no maml or comment-based help. - # then help engine put string outside of 'text' property - # In this case there is no DescriptionToPara call needed - $ParameterObject.Description = $HelpEntry.description | AddLineBreaksForParagraphs - } - } - - $syntaxParam = $Help.syntax.syntaxItem.parameter | Where-Object {$_.Name -eq $Parameter.Name} | Select-Object -First 1 - if ($syntaxParam) - { - # otherwise we could potentialy get it from Reflection but not doing it for now - foreach ($parameterValue in $syntaxParam.parameterValueGroup.parameterValue) - { - $ParameterObject.parameterValueGroup.Add($parameterValue) - } - } - } - - function FillUpSyntaxFromCommand - { - foreach($ParameterSet in $Command.ParameterSets) - { - $SyntaxObject = New-Object -TypeName Markdown.MAML.Model.MAML.MamlSyntax - - $SyntaxObject.ParameterSetName = $ParameterSet.Name - $SyntaxObject.IsDefault = $ParameterSet.IsDefault - - foreach($Parameter in $ParameterSet.Parameters) - { - # ignore CommonParameters - if (isCommonParameterName $Parameter.Name -Workflow:$IsWorkflow) - { - # but don't ignore them, if they have explicit help entries - if ($Help.parameters.parameter | Where-Object {$_.Name -eq $Parameter.Name}) - { - } - else - { - continue - } - } - - $hasDontShow = $false - $hasSupportsWildsCards = $false - - foreach ($Attribute in $Parameter.Attributes) - { - if ($ExcludeDontShow) - { - if ($Attribute.TypeId.ToString() -eq 'System.Management.Automation.ParameterAttribute' -and $Attribute.DontShow) - { - $hasDontShow = $true - } - } - - if ($Attribute.TypeId.ToString() -eq 'System.Management.Automation.SupportsWildcardsAttribute') - { - $hasSupportsWildsCards = $true - } - } - - if ($hasDontShow) - { - continue - } - - $ParameterObject = New-Object -TypeName Markdown.MAML.Model.MAML.MamlParameter - $ParameterObject.Name = $Parameter.Name - $ParameterObject.Required = $Parameter.IsMandatory - $ParameterObject.PipelineInput = getPipelineValue $Parameter - $ParameterObject.Globbing = $hasSupportsWildsCards - # the ParameterType could be just a string in case of remoting - # or a TypeInfo object, in the regular case - if ($Session) { - # in case of remoting we already pre-calcuated the Type string - $ParameterObject.Type = $Parameter.ParameterTypeName - } else { - $ParameterObject.Type = GetTypeString -TypeObject $Parameter.ParameterType - } - # ToString() works in both cases - $ParameterObject.FullType = $Parameter.ParameterType.ToString() - - $ParameterObject.ValueRequired = -not ($Parameter.Type -eq "SwitchParameter") # thisDefinition is a heuristic - - foreach($Alias in $Parameter.Aliases) - { - $ParameterObject.Aliases += $Alias - } - - $ParameterObject.Description = if ([String]::IsNullOrEmpty($Parameter.HelpMessage)) - { - # additional new-lines are needed for Update-MarkdownHelp scenario. - switch ($Parameter.Name) - { - # we have well-known parameters and can generate a reasonable description for them - # https://github.com/PowerShell/platyPS/issues/211 - 'Confirm' { $LocalizedData.Confirm + "`r`n`r`n" } - 'WhatIf' { $LocalizedData.WhatIf + "`r`n`r`n" } - 'IncludeTotalCount' { $LocalizedData.IncludeTotalCount + "`r`n`r`n" } - 'Skip' { $LocalizedData.Skip + "`r`n`r`n" } - 'First' { $LocalizedData.First + "`r`n`r`n" } - default { ($LocalizedData.ParameterDescription -f $Parameter.Name) + "`r`n`r`n" } - } - } - else - { - $Parameter.HelpMessage - } - - FillUpParameterFromHelp $ParameterObject - - $SyntaxObject.Parameters.Add($ParameterObject) - } - - $MamlCommandObject.Syntax.Add($SyntaxObject) - } - } - - function FillUpSyntaxFromHelp - { - function GuessTheType - { - param([string]$type) - - if (-not $type) - { - # weired, but that's how it works - return 'SwitchParameter' - } - - return $type - } - - $ParamSetCount = 0 - foreach($ParameterSet in $Help.syntax.syntaxItem) - { - $SyntaxObject = New-Object -TypeName Markdown.MAML.Model.MAML.MamlSyntax - - $ParamSetCount++ - $SyntaxObject.ParameterSetName = $script:SET_NAME_PLACEHOLDER + "_" + $ParamSetCount - - foreach($Parameter in $ParameterSet.Parameter) - { - $ParameterObject = New-Object -TypeName Markdown.MAML.Model.MAML.MamlParameter - - $ParameterObject.Type = GuessTheType $Parameter.parameterValue - - $ParameterObject.Name = $Parameter.Name - $ParameterObject.Required = $Parameter.required -eq 'true' - $ParameterObject.PipelineInput = $Parameter.pipelineInput | normalizeFirstLatter - - $ParameterObject.ValueRequired = -not ($ParameterObject.Type -eq "SwitchParameter") # thisDefinition is a heuristic - - if ($parameter.Aliases -ne 'None') - { - $ParameterObject.Aliases = $parameter.Aliases - } - - FillUpParameterFromHelp $ParameterObject - - $SyntaxObject.Parameters.Add($ParameterObject) - } - - $MamlCommandObject.Syntax.Add($SyntaxObject) - } - } - - if ($UseHelpForParametersMetadata) - { - FillUpSyntaxFromHelp - } - else - { - FillUpSyntaxFromCommand - } - - #endregion - ########## - - #####GET THE HELP-Object Content and add it to the MAML Object##### - #region Help-Object processing - - #Get Synopsis - if ($UsePlaceholderForSynopsis) - { - # Help object ALWAYS contains SYNOPSIS. - # If it's not available, it's auto-generated. - # We don't want to include auto-generated SYNOPSIS (see https://github.com/PowerShell/platyPS/issues/110) - $MamlCommandObject.Synopsis = New-Object -TypeName Markdown.MAML.Model.Markdown.SectionBody ($LocalizedData.Synopsis) - } - else - { - $MamlCommandObject.Synopsis = New-Object -TypeName Markdown.MAML.Model.Markdown.SectionBody ( - # $Help.Synopsis only contains the first paragraph - # https://github.com/PowerShell/platyPS/issues/328 - $Help.details.description | - DescriptionToPara | - AddLineBreaksForParagraphs - ) - } - - #Get Description - if($Help.description -ne $null) - { - $MamlCommandObject.Description = New-Object -TypeName Markdown.MAML.Model.Markdown.SectionBody ( - $Help.description | - DescriptionToPara | - AddLineBreaksForParagraphs - ) - } - - #Add to Notes - #From the Help AlertSet data - if($help.alertSet) - { - $MamlCommandObject.Notes = New-Object -TypeName Markdown.MAML.Model.Markdown.SectionBody ( - $help.alertSet.alert | - DescriptionToPara | - AddLineBreaksForParagraphs - ) - } - - # Not provided by the command object. Using the Command Type to create a note declaring it's type. - # We can add this placeholder - - - #Add to relatedLinks - if($help.relatedLinks) - { - foreach($link in $Help.relatedLinks.navigationLink) - { - $mamlLink = New-Object -TypeName Markdown.MAML.Model.MAML.MamlLink - $mamlLink.LinkName = $link.linkText - $mamlLink.LinkUri = $link.uri - $MamlCommandObject.Links.Add($mamlLink) - } - } - - #Add Examples - foreach($Example in $Help.examples.example) - { - $MamlExampleObject = New-Object -TypeName Markdown.MAML.Model.MAML.MamlExample - - $MamlExampleObject.Introduction = $Example.introduction - $MamlExampleObject.Title = $Example.title - $MamlExampleObject.Code = @( - New-Object -TypeName Markdown.MAML.Model.MAML.MamlCodeBlock ($Example.code, '') - ) - - $RemarkText = $Example.remarks | - DescriptionToPara | - AddLineBreaksForParagraphs - - $MamlExampleObject.Remarks = $RemarkText - $MamlCommandObject.Examples.Add($MamlExampleObject) - } - - #Get Inputs - #Reccomend adding a Parameter Name and Parameter Set Name to each input object. - #region Inputs - $Inputs = @() - - $Help.inputTypes.inputType | ForEach-Object { - $InputDescription = $_.description - $inputtypes = $_.type.name - if ($_.description -eq $null -and $_.type.name -ne $null) - { - $inputtypes = $_.type.name.split("`n", [System.StringSplitOptions]::RemoveEmptyEntries) - } - - $inputtypes | ForEach-Object { - $InputObject = New-Object -TypeName Markdown.MAML.Model.MAML.MamlInputOutput - $InputObject.TypeName = $_ - $InputObject.Description = $InputDescription | - DescriptionToPara | - AddLineBreaksForParagraphs - $Inputs += $InputObject - } - } - - foreach($Input in $Inputs) {$MamlCommandObject.Inputs.Add($Input)} - - #endregion - - #Get Outputs - #No Output Type description is provided from the command object. - #region Outputs - $Outputs = @() - - $Help.returnValues.returnValue | ForEach-Object { - $OuputDescription = $_.description - $Outputtypes = $_.type.name - if ($_.description -eq $null -and $_.type.name -ne $null) - { - $Outputtypes = $_.type.name.split("`n", [System.StringSplitOptions]::RemoveEmptyEntries) - } - - $Outputtypes | ForEach-Object { - $OutputObject = New-Object -TypeName Markdown.MAML.Model.MAML.MamlInputOutput - $OutputObject.TypeName = $_ - $OutputObject.Description = $OuputDescription | - DescriptionToPara | - AddLineBreaksForParagraphs - $Outputs += $OutputObject - } - } - - foreach($Output in $Outputs) {$MamlCommandObject.Outputs.Add($Output)} - #endregion - ########## - - #####Adding Parameters Section from Syntax block##### - #region Parameter Unique Selection from Parameter Sets - #This will only work when the Parameters member has a public set as well as a get. - - function Get-ParameterByName - { - param( - [string]$Name - ) - - $defaultSyntax = $MamlCommandObject.Syntax | Where-Object { $Command.DefaultParameterSet -eq $_.ParameterSetName } - # default syntax should have a priority - $syntaxes = @($defaultSyntax) + $MamlCommandObject.Syntax - - foreach ($s in $syntaxes) - { - $param = $s.Parameters | Where-Object { $_.Name -eq $Name } - if ($param) - { - return $param - } - } - } - - function Get-ParameterNamesOrder() - { - # we want to keep original order for existing help - # if something changed: - # - remove it from it's position - # - add to the end - - $helpNames = $Help.parameters.parameter.Name - if (-not $helpNames) { $helpNames = @() } - - # sort-object unique does case-insensiteve unification - $realNames = $MamlCommandObject.Syntax.Parameters.Name | Sort-object -Unique - if (-not $realNames) { $realNames = @() } - - $realNamesList = New-Object 'System.Collections.Generic.List[string]' - $realNamesList.AddRange( ( [string[]] $realNames) ) - - foreach ($name in $helpNames) - { - if ($realNamesList.Remove($name)) - { - # yeild - $name - } - # Otherwise it didn't exist - } - - foreach ($name in $realNamesList) - { - # yeild - $name - } - - } - - foreach($ParameterName in (Get-ParameterNamesOrder)) - { - $Parameter = Get-ParameterByName $ParameterName - if ($Parameter) - { - if ($UseFullTypeName) - { - $Parameter = $Parameter.Clone() - $Parameter.Type = $Parameter.FullType - } - $MamlCommandObject.Parameters.Add($Parameter) - } - else - { - Write-Warning -Message ($LocalizedData.ParameterNotFound -f '[Markdown generation]', $ParameterName, $Command.Name) - } - } - - # Handle CommonParameters, default for MamlCommand is SupportCommonParameters = $true - if ($Command.CmdletBinding -eq $false) - { - # Remove CommonParameters by exception - $MamlCommandObject.SupportCommonParameters = $false - } - - # Handle CommonWorkflowParameters - $MamlCommandObject.IsWorkflow = $IsWorkflow - - #endregion - ########## - - return $MamlCommandObject -} - -function validateWorkingProvider -{ - if((Get-Location).Drive.Provider.Name -ne 'FileSystem') - { - Write-Verbose -Message $LocalizedData.SettingFileSystemProvider - $AvailableFileSystemDrives = Get-PSDrive | Where-Object {$_.Provider.Name -eq "FileSystem"} | Select-Object Root - if($AvailableFileSystemDrives.Count -gt 0) - { - Set-Location $AvailableFileSystemDrives[0].Root - } - else - { - throw $LocalizedData.FailedSettingFileSystemProvider - } - } -} -#endregion - -#region Parameter Auto Completers - - -# bbbbbbbb -# TTTTTTTTTTTTTTTTTTTTTTT b::::::b CCCCCCCCCCCCC lllllll tttt iiii -# T:::::::::::::::::::::T b::::::b CCC::::::::::::C l:::::l ttt:::t i::::i -# T:::::::::::::::::::::T b::::::b CC:::::::::::::::C l:::::l t:::::t iiii -# T:::::TT:::::::TT:::::T b:::::b C:::::CCCCCCCC::::C l:::::l t:::::t -# TTTTTT T:::::T TTTTTTaaaaaaaaaaaaa b:::::bbbbbbbbb C:::::C CCCCCC ooooooooooo mmmmmmm mmmmmmm ppppp ppppppppp l::::l eeeeeeeeeeee ttttttt:::::ttttttt iiiiiii ooooooooooo nnnn nnnnnnnn -# T:::::T a::::::::::::a b::::::::::::::bb C:::::C oo:::::::::::oo mm:::::::m m:::::::mm p::::ppp:::::::::p l::::l ee::::::::::::ee t:::::::::::::::::t i:::::i oo:::::::::::oo n:::nn::::::::nn -# T:::::T aaaaaaaaa:::::a b::::::::::::::::b C:::::C o:::::::::::::::om::::::::::mm::::::::::mp:::::::::::::::::p l::::l e::::::eeeee:::::eet:::::::::::::::::t i::::i o:::::::::::::::on::::::::::::::nn -# T:::::T a::::a b:::::bbbbb:::::::b --------------- C:::::C o:::::ooooo:::::om::::::::::::::::::::::mpp::::::ppppp::::::p l::::l e::::::e e:::::etttttt:::::::tttttt i::::i o:::::ooooo:::::onn:::::::::::::::n -# T:::::T aaaaaaa:::::a b:::::b b::::::b -:::::::::::::- C:::::C o::::o o::::om:::::mmm::::::mmm:::::m p:::::p p:::::p l::::l e:::::::eeeee::::::e t:::::t i::::i o::::o o::::o n:::::nnnn:::::n -# T:::::T aa::::::::::::a b:::::b b:::::b --------------- C:::::C o::::o o::::om::::m m::::m m::::m p:::::p p:::::p l::::l e:::::::::::::::::e t:::::t i::::i o::::o o::::o n::::n n::::n -# T:::::T a::::aaaa::::::a b:::::b b:::::b C:::::C o::::o o::::om::::m m::::m m::::m p:::::p p:::::p l::::l e::::::eeeeeeeeeee t:::::t i::::i o::::o o::::o n::::n n::::n -# T:::::T a::::a a:::::a b:::::b b:::::b C:::::C CCCCCCo::::o o::::om::::m m::::m m::::m p:::::p p::::::p l::::l e:::::::e t:::::t tttttt i::::i o::::o o::::o n::::n n::::n -# TT:::::::TT a::::a a:::::a b:::::bbbbbb::::::b C:::::CCCCCCCC::::Co:::::ooooo:::::om::::m m::::m m::::m p:::::ppppp:::::::pl::::::le::::::::e t::::::tttt:::::ti::::::io:::::ooooo:::::o n::::n n::::n -# T:::::::::T a:::::aaaa::::::a b::::::::::::::::b CC:::::::::::::::Co:::::::::::::::om::::m m::::m m::::m p::::::::::::::::p l::::::l e::::::::eeeeeeee tt::::::::::::::ti::::::io:::::::::::::::o n::::n n::::n -# T:::::::::T a::::::::::aa:::ab:::::::::::::::b CCC::::::::::::C oo:::::::::::oo m::::m m::::m m::::m p::::::::::::::pp l::::::l ee:::::::::::::e tt:::::::::::tti::::::i oo:::::::::::oo n::::n n::::n -# TTTTTTTTTTT aaaaaaaaaa aaaabbbbbbbbbbbbbbbb CCCCCCCCCCCCC ooooooooooo mmmmmm mmmmmm mmmmmm p::::::pppppppp llllllll eeeeeeeeeeeeee ttttttttttt iiiiiiii ooooooooooo nnnnnn nnnnnn -# p:::::p -# p:::::p -# p:::::::p -# p:::::::p -# p:::::::p -# ppppppppp - - -# Register-ArgumentCompleter can be provided thru TabExpansionPlusPlus or with V5 inbox module. -# We don't care much which one it is, but the inbox one doesn't have -Description parameter -if (Get-Command -Name Register-ArgumentCompleter -Module TabExpansionPlusPlus -ErrorAction Ignore) { - Function ModuleNameCompleter { - Param ( - $commandName, - $parameterName, - $wordToComplete, - $commandAst, - $fakeBoundParameter - ) - - Get-Module -Name "$wordToComplete*" | - ForEach-Object { - New-CompletionResult -CompletionText $_.Name -ToolTip $_.Description - } - } - - Register-ArgumentCompleter -CommandName New-MarkdownHelp -ParameterName Module -ScriptBlock $Function:ModuleNameCompleter -Description 'This argument completer handles the -Module parameter of the New-MarkdownHelp Command.' -} -elseif (Get-Command -Name Register-ArgumentCompleter -ErrorAction Ignore) { - Function ModuleNameCompleter { - Param ( - $commandName, - $parameterName, - $wordToComplete, - $commandAst, - $fakeBoundParameter - ) - - Get-Module -Name "$wordToComplete*" | - ForEach-Object { - $_.Name - } - } - - Register-ArgumentCompleter -CommandName New-MarkdownHelp -ParameterName Module -ScriptBlock $Function:ModuleNameCompleter -} - -#endregion Parameter Auto Completers diff --git a/v1/templates/aboutTemplate.md b/v1/templates/aboutTemplate.md deleted file mode 100644 index d6ea723f..00000000 --- a/v1/templates/aboutTemplate.md +++ /dev/null @@ -1,57 +0,0 @@ -# {{TOPIC NAME}} -## {{FileNameForHelpSystem}} - -``` -ABOUT TOPIC NOTE: -The first header of the about topic should be the topic name. -The second header contains the lookup name used by the help system. - -IE: -# Some Help Topic Name -## SomeHelpTopicFileName - -This will be transformed into the text file -as `about_SomeHelpTopicFileName`. -Do not include file extensions. -The second header should have no spaces. -``` - -# SHORT DESCRIPTION -{{ Short Description Placeholder }} - -``` -ABOUT TOPIC NOTE: -About topics can be no longer than 80 characters wide when rendered to text. -Any topics greater than 80 characters will be automatically wrapped. -The generated about topic will be encoded UTF-8. -``` - -# LONG DESCRIPTION -{{ Long Description Placeholder }} - -## Optional Subtopics -{{ Optional Subtopic Placeholder }} - -# EXAMPLES -{{ Code or descriptive examples of how to leverage the functions described. }} - -# NOTE -{{ Note Placeholder - Additional information that a user needs to know.}} - -# TROUBLESHOOTING NOTE -{{ Troubleshooting Placeholder - Warns users of bugs}} - -{{ Explains behavior that is likely to change with fixes }} - -# SEE ALSO -{{ See also placeholder }} - -{{ You can also list related articles, blogs, and video URLs. }} - -# KEYWORDS -{{List alternate names or titles for this topic that readers might use.}} - -- {{ Keyword Placeholder }} -- {{ Keyword Placeholder }} -- {{ Keyword Placeholder }} -- {{ Keyword Placeholder }} \ No newline at end of file diff --git a/v1/test/Markdown.MAML.Test/Common.cs b/v1/test/Markdown.MAML.Test/Common.cs deleted file mode 100644 index 1a5990b5..00000000 --- a/v1/test/Markdown.MAML.Test/Common.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using Markdown.MAML.Renderer; -using Xunit; - -namespace Markdown.MAML.Test -{ - public static class Common - { - public static void AssertMultilineEqual(string expected, string actual) - { - Assert.Equal(RenderCleaner.NormalizeLineBreaks(expected), - RenderCleaner.NormalizeLineBreaks(actual)); - } - } -} diff --git a/v1/test/Markdown.MAML.Test/EndToEnd/EndToEndTests.cs b/v1/test/Markdown.MAML.Test/EndToEnd/EndToEndTests.cs deleted file mode 100644 index ef7dff64..00000000 --- a/v1/test/Markdown.MAML.Test/EndToEnd/EndToEndTests.cs +++ /dev/null @@ -1,547 +0,0 @@ -using System.Collections.Generic; -using System.Xml; -using System.Xml.XPath; -using Markdown.MAML.Renderer; -using Xunit; -using Markdown.MAML.Parser; -using Markdown.MAML.Transformer; -using System.Linq; - -namespace Markdown.MAML.Test.EndToEnd -{ - public class EndToEndTests - { - [Fact] - public void ProduceMamlFromMarkdown() - { - string maml = MarkdownStringToMamlString(@" -# Get-Foo -## Synopsis -This is Synopsis -## Examples -### Example 1 -``` -PS C:\> Update-MarkdownHelp -``` - -This is example 1 remark. - -### Example 2: With a long title -This is an example description. - -``` -PS C:\> Update-MarkdownHelp -``` - -This is example 2 remark. -"); - string[] name = GetXmlContent(maml, "/msh:helpItems/command:command/command:details/command:name"); - Assert.Single(name); - Assert.Equal("Get-Foo", name[0]); - - string[] synopsis = GetXmlContent(maml, "/msh:helpItems/command:command/command:details/maml:description/maml:para"); - Assert.Single(synopsis); - Assert.Equal("This is Synopsis", synopsis[0]); - - // Check that example title is reproduced with dash (-) padding - string[] example = EndToEndTests.GetXmlContent(maml, "/msh:helpItems/command:command/command:examples/command:example/maml:title"); - Assert.Equal(63, example[0].Length); - Assert.Equal(64, example[1].Length); - Assert.Matches($"^-+ Example 1 -+$", example[0]); - Assert.Matches($"^-+ Example 2: With a long title -+$", example[1]); - } - - [Fact] - public void ProduceMultilineDescription() - { - string maml = MarkdownStringToMamlString(@" -# Get-Foo -## Synopsis -This is Synopsis, but it doesn't matter in this test - -## DESCRIPTION -Hello, - -I'm a multiline description. - -And this is my last line. -"); - - string[] description = GetXmlContent(maml, "/msh:helpItems/command:command/maml:description/maml:para"); - Assert.Equal(3, description.Length); - } - - [Fact] - public void PreserveMarkdownWhenUpdatingMarkdownHelp() - { - var expected = @"# Update-MarkdownHelp - -## SYNOPSIS - -Example markdown to test that markdown is preserved. - -## SYNTAX - -``` -Update-MarkdownHelp [-Name] <String> [-Path <String>] -``` - -## DESCRIPTION -When calling Update-MarkdownHelp line breaks should be preserved. - -## EXAMPLES - -### Example 1: With no line break or description -```powershell -PS C:\> Write-Host 'This is output.' -``` - -``` -This is output. -``` - -This is example 1 remark. - -### Example 2: With no line break -This is an example description. - -```powershell -PS C:\> Update-MarkdownHelp -``` - -This is example 2 remark. - -### Example 3: With line break and no description - -```powershell -PS C:\> Update-MarkdownHelp -``` - -This is example 3 remark. - -### Example 4: With line break and description - -This is an example description. - -```preserve -PS C:\> Update-MarkdownHelp -``` - -```text -Output -``` - -This is example 4 remark. - -## PARAMETERS - -### -Name - -Parameter name description with line break. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: True -Position: 1 -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Path -Parameter path description with no line break. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -## INPUTS - -### String[] - -This is an input description. - -## OUTPUTS - -### System.Object - -This is an output description. - -## NOTES - -## RELATED LINKS -"; - - // Parse markdown and convert back to markdown to make sure there are no changes - var actualFull = MarkdownStringToMarkdownString(expected, ParserMode.Full); - var actualFormattingPreserve = MarkdownStringToMarkdownString(expected, ParserMode.FormattingPreserve); - - Common.AssertMultilineEqual(expected, actualFull); - Common.AssertMultilineEqual(expected, actualFormattingPreserve); - } - - [Fact] - public void CanUseSharpInsideParagraphs() - { - string maml = MarkdownStringToMamlString(@" -# Get-Foo -## Synopsis -This is Synopsis #hashtagNotAHeader. - -## DESCRIPTION -I'm description -"); - - string[] description = GetXmlContent(maml, "/msh:helpItems/command:command/maml:description/maml:para"); - Assert.Single(description); - Assert.Equal("I'm description", description[0]); - - string[] synopsis = GetXmlContent(maml, "/msh:helpItems/command:command/command:details/maml:description/maml:para"); - Assert.Single(synopsis); - Assert.Equal("This is Synopsis #hashtagNotAHeader.", synopsis[0]); - } - - [Fact] - public void CanUseRelativeLinksInRelatedLinksSection() - { - // more details: https://github.com/PowerShell/platyPS/issues/164 - - string maml = MarkdownStringToMamlString(@" -# Get-Foo - -## RELATED LINKS - -[foo](foo.md) -[bar](bar://bar.md) -"); - - string[] linkText = GetXmlContent(maml, "/msh:helpItems/command:command/command:relatedLinks/maml:navigationLink/maml:linkText"); - Assert.Equal(2, linkText.Length); - Assert.Equal("foo", linkText[0]); - Assert.Equal("bar", linkText[1]); - - string[] linkUri = GetXmlContent(maml, "/msh:helpItems/command:command/command:relatedLinks/maml:navigationLink/maml:uri"); - Assert.Equal(2, linkUri.Length); - Assert.Equal("", linkUri[0]); // empty, because foo.md is not a valid URI and help system will be unhappy. - Assert.Equal("bar://bar.md", linkUri[1]); // bar://bar.md is a valid URI - } - - [Fact] - public void CanProcessAddHistoryAddSnapinMarkdownWithoutErrors() - { - string maml = MarkdownStringToMamlString(@" -# Add-History - -## SYNOPSIS -Appends entries to the session history. - -## DESCRIPTION -The Add-History cmdlet adds entries to the end of the session history, that is, the list of commands entered during the current session. -You can use the Get-History cmdlet to get the commands and pass them to Add-History, or you can export the commands to a CSV or XML file, then import the commands, and pass the imported file to Add-History. You can use this cmdlet to add specific commands to the history or to create a single history file that includes commands from more than one session. - -## PARAMETERS - -### InputObject [PSObject[]] - -```powershell -[Parameter( - Position = 1, - ValueFromPipeline = $true, - ParameterSetName = 'Set 1')] -``` - -Adds the specified HistoryInfo object to the session history. You can use this parameter to submit a HistoryInfo object, such as the ones that are returned by the Get-History, Import-Clixml, or Import-Csv cmdlets, to Add-History. - -### Passthru [switch] - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -Returns a history object for each history entry. By default, this cmdlet does not generate any output. - - -## INPUTS -### Microsoft.PowerShell.Commands.HistoryInfo -You can pipe a HistoryInfo object to Add-History. - -## OUTPUTS -### None or Microsoft.PowerShell.Commands.HistoryInfo -When you use the PassThru parameter, Add-History returns a HistoryInfo object. Otherwise, this cmdlet does not generate any output. - -## NOTES -The session history is a list of the commands entered during the session along with the ID. The session history represents the order of execution, the status, and the start and end times of the command. As you enter each command, Windows PowerShell adds it to the history so that you can reuse it. For more information about the session history, see about_History. -To specify the commands to add to the history, use the InputObject parameter. The Add-History command accepts only HistoryInfo objects, such as those returned for each command by the Get-History cmdlet. You cannot pass it a path and file name or a list of commands. -You can use the InputObject parameter to pass a file of HistoryInfo objects to Add-History. To do so, export the results of a Get-History command to a file by using the Export-Csv or Export-Clixml cmdlet and then import the file by using the Import-Csv or Import-Clixml cmdlets. You can then pass the file of imported HistoryInfo objects to Add-History through a pipeline or in a variable. For more information, see the examples. -The file of HistoryInfo objects that you pass to the Add-History cmdlet must include the type information, column headings, and all of the properties of the HistoryInfo objects. If you intend to pass the objects back to Add-History, do not use the NoTypeInformation parameter of the Export-Csv cmdlet and do not delete the type information, column headings, or any fields in the file. -To edit the session history, export the session to a CSV or XML file, edit the file, import the file, and use Add-History to append it to the current session history. - - -## EXAMPLES -### -------------------------- EXAMPLE 1 -------------------------- - -```powershell -PS C:\>get-history | export-csv c:\testing\history.csv -PS C:\>import-csv history.csv | add-history - -``` -These commands add the commands typed in one Windows PowerShell session to the history of a different Windows PowerShell session. The first command gets objects representing the commands in the history and exports them to the History.csv file. The second command is typed at the command line of a different session. It uses the Import-Csv cmdlet to import the objects in the History.csv file. The pipeline operator passes the objects to the Add-History cmdlet, which adds the objects representing the commands in the History.csv file to the current session history. - - - - - - -### -------------------------- EXAMPLE 2 -------------------------- - -```powershell -PS C:\>import-clixml c:\temp\history.xml | add-history -passthru | foreach-object -process {invoke-history} - -``` -This command imports commands from the History.xml file, adds them to the current session history, and then executes the commands in the combined history. -The first command uses the Import-Clixml cmdlet to import a command history that was exported to the History.xml file. The pipeline operator (|) passes the commands to the Add-History parameter, which adds the commands to the current session history. The PassThru parameter passes the objects representing the added commands down the pipeline. -The command then uses the ForEach-Object cmdlet to apply the Invoke-History command to each of the commands in the combined history. The Invoke-History command is formatted as a script block (enclosed in braces) as required by the Process parameter of the ForEach-Object cmdlet. - - - - - - -### -------------------------- EXAMPLE 3 -------------------------- - -```powershell -PS C:\>get-history -id 5 -count 5 | add-history - -``` -This command adds the first five commands in the history to the end of the history list. It uses the Get-History cmdlet to get the five commands ending in command 5. The pipeline operator (|) passes them to the Add-History cmdlet, which appends them to the current history. The Add-History command does not include any parameters, but Windows PowerShell associates the objects passed through the pipeline with the InputObject parameter of Add-History. - - - - - - -### -------------------------- EXAMPLE 4 -------------------------- - -```powershell -PS C:\>$a = import-csv c:\testing\history.csv -PS C:\>add-history -inputobject $a -passthru - -``` -These commands add the commands in the History.csv file to the current session history. The first command uses the Import-Csv cmdlet to import the commands in the History.csv file and store its contents in the variable $a. The second command uses the Add-History cmdlet to add the commands from History.csv to the current session history. It uses the InputObject parameter to specify the $a variable and the PassThru parameter to generate an object to display at the command line. Without the PassThru parameter, the Add-History cmdlet does not generate any output. - - - - - - -### -------------------------- EXAMPLE 5 -------------------------- - -```powershell -PS C:\>add-history -inputobject (import-clixml c:\temp\history01.xml) - -``` -This command adds the commands in the History01.xml file to the current session history. It uses the InputObject parameter to pass the results of the command in parentheses to the Add-History cmdlet. The command in parentheses, which is executed first, imports the History01.xml file into Windows PowerShell. The Add-History cmdlet then adds the commands in the file to the session history. - - - - - - - -## RELATED LINKS -[Online Version:](http://go.microsoft.com/fwlink/p/?linkid=289569) -[Clear-History]() -[Get-History]() -[Invoke-History]() -[about_History]() - -# Add-PSSnapin - -## SYNOPSIS -Adds one or more Windows PowerShell snap-ins to the current session. - -## DESCRIPTION -The Add-PSSnapin cmdlet adds registered Windows PowerShell snap-ins to the current session. After the snap-ins are added, you can use the cmdlets and providers that the snap-ins support in the current session. -To add the snap-in to all future Windows PowerShell sessions, add an Add-PSSnapin command to your Windows PowerShell profile. For more information, see about_Profiles. -Beginning in Windows PowerShell 3.0, the core commands that are included in Windows PowerShell are packaged in modules. The exception is Microsoft.PowerShell.Core, which is a snap-in (PSSnapin). By default, only the Microsoft.PowerShell.Core snap-in is added to the session. Modules are imported automatically on first use and you can use the Import-Module cmdlet to import them. - -## PARAMETERS - -### Name [String[]] - -```powershell -[Parameter( - Mandatory = $true, - Position = 1, - ValueFromPipelineByPropertyName = $true, - ParameterSetName = 'Set 1')] -``` - -Specifies the name of the snap-in. (This is the Name, not the AssemblyName or ModuleName.) Wildcards are permitted. -To find the names of the registered snap-ins on your system, type: ""get-pssnapin -registered"". - -### PassThru [switch] - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -Returns an object representing each added snap-in. By default, this cmdlet does not generate any output. - - -## INPUTS -### None -You cannot pipe objects to Add-PSSnapin. - -## OUTPUTS -### None or System.Management.Automation.PSSnapInInfo -When you use the PassThru parameter, Add-PSSnapin returns a PSSnapInInfo object that represents the snap-in. Otherwise, this cmdlet does not generate any output. - -## NOTES -Beginning in Windows PowerShell 3.0, the core commands that are installed with Windows PowerShell are packaged in modules. In Windows PowerShell 2.0, and in host programs that create older-style sessions in later versions of Windows PowerShell, the core commands are packaged in snap-ins (""PSSnapins""). The exception is Microsoft.PowerShell.Core, which is always a snap-in. Also, remote sessions, such as those started by the New-PSSession cmdlet, are older-style sessions that include core snap-ins. -For information about the CreateDefault2 method that creates newer-style sessions with core modules, see ""CreateDefault2 Method"" in MSDN at [http://msdn.microsoft.com/en-us/library/windows/desktop/system.management.automation.runspaces.initialsessionstate.createdefault2(v=VS.85).aspx](). -For detailed information about snap-ins in Windows PowerShell, see about_Pssnapins. For information about how to create a Windows PowerShell snap-in, see ""How to Create a Windows PowerShell Snap-in"" in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?LinkId=144762http://go.microsoft.com/fwlink/?LinkId=144762. -Add-PSSnapin adds the snap-in only to the current session. To add the snap-in to all Windows PowerShell sessions, add it to your Windows PowerShell profile. For more information, see about_Profiles. -You can add any Windows PowerShell snap-in that has been registered by using the Microsoft .NET Framework install utility. For more information, see ""How to Register Cmdlets, Providers, and Host Applications"" in the MSDN library at http://go.microsoft.com/fwlink/?LinkID=143619http://go.microsoft.com/fwlink/?LinkID=143619. -To get a list of snap-ins that are registered on your computer, type get-pssnapin -registered. -Before adding a snap-in, Add-PSSnapin checks the version of the snap-in to verify that it is compatible with the current version of Windows PowerShell. If the snap-in fails the version check, Windows PowerShell reports an error. - -## EXAMPLES -### -------------------------- EXAMPLE 1 -------------------------- - -```powershell -PS C:\>add-PSSnapIn Microsoft.Exchange, Microsoft.Windows.AD - -``` -This command adds the Microsoft Exchange and Active Directory snap-ins to the current session. - - - - - - -### -------------------------- EXAMPLE 2 -------------------------- - -```powershell -PS C:\>get-pssnapin -registered | add-pssnapin -passthru - -``` -This command adds all of the registered Windows PowerShell snap-ins to the session. It uses the Get-PSSnapin cmdlet with the Registered parameter to get objects representing each of the registered snap-ins. The pipeline operator (|) passes the result to Add-PSSnapin, which adds them to the session. The PassThru parameter returns objects that represent each of the added snap-ins. - - - - - - -### -------------------------- EXAMPLE 3 -------------------------- - -```powershell -The first command gets snap-ins that have been added to the current session, including the snap-ins that are installed with Windows PowerShell. In this example, ManagementFeatures is not returned. This indicates that it has not been added to the session. -PS C:\>get-pssnapin - -The second command gets snap-ins that have been registered on your system (including those that have already been added to the session). It does not include the snap-ins that are installed with Windows PowerShell.In this case, the command does not return any snap-ins. This indicates that the ManagementFeatures snapin has not been registered on the system. -PS C:\>get-pssnapin -registered - -The third command creates an alias, ""installutil"", for the path to the InstallUtil tool in .NET Framework. -PS C:\>set-alias installutil $env:windir\Microsoft.NET\Framework\v2.0.50727\installutil.exe - -The fourth command uses the InstallUtil tool to register the snap-in. The command specifies the path to ManagementCmdlets.dll, the file name or ""module name"" of the snap-in. -PS C:\>installutil C:\Dev\Management\ManagementCmdlets.dll - -The fifth command is the same as the second command. This time, you use it to verify that the ManagementCmdlets snap-in is registered. -PS C:\>get-pssnapin -registered - -The sixth command uses the Add-PSSnapin cmdlet to add the ManagementFeatures snap-in to the session. It specifies the name of the snap-in, ManagementFeatures, not the file name. -PS C:\>add-pssnapin ManagementFeatures - -To verify that the snap-in is added to the session, the seventh command uses the Module parameter of the Get-Command cmdlet. It displays the items that were added to the session by a snap-in or module. -PS C:\>get-command -module ManagementFeatures - -You can also use the PSSnapin property of the object that the Get-Command cmdlet returns to find the snap-in or module in which a cmdlet originated. The eighth command uses dot notation to find the value of the PSSnapin property of the Set-Alias cmdlet. -PS C:\>(get-command set-alias).pssnapin - -``` -This example demonstrates the process of registering a snap-in on your system and then adding it to your session. It uses ManagementFeatures, a fictitious snap-in implemented in a file called ManagementCmdlets.dll. - - - -## RELATED LINKS -[Online Version:](http://go.microsoft.com/fwlink/p/?linkid=289570) -[Get-PSSnapin]() -[Remove-PSSnapin]() -[about_Profiles]() -[about_PSSnapins]() - -"); - string[] examples = GetXmlContent(maml, "msh:helpItems/command:command/command:examples/command:example/dev:code"); - Assert.Equal(5 + 3, examples.Length); - } - - public static string[] GetXmlContent(string xml, string xpath) - { - List<string> result = new List<string>(); - XmlDocument xmlDoc = new XmlDocument(); - xmlDoc.LoadXml(xml); - var nav = xmlDoc.CreateNavigator(); - - XmlNamespaceManager xmlns = new XmlNamespaceManager(nav.NameTable); - xmlns.AddNamespace("command", "http://schemas.microsoft.com/maml/dev/command/2004/10"); - xmlns.AddNamespace("maml", "http://schemas.microsoft.com/maml/2004/10"); - xmlns.AddNamespace("dev", "http://schemas.microsoft.com/maml/dev/2004/10"); - xmlns.AddNamespace("MSHelp", "http://msdn.microsoft.com/mshelp"); - xmlns.AddNamespace("msh", "http://msh"); - - XPathNodeIterator iterator = nav.Select(xpath, xmlns); - foreach (var i in iterator) - { - result.Add(i.ToString().Trim()); - } - - return result.ToArray(); - } - - /// <summary> - /// This is a helper method to do all 3 steps. - /// </summary> - /// <param name="markdown"></param> - /// <returns></returns> - public static string MarkdownStringToMamlString(string markdown) - { - var parser = new MarkdownParser(); - var transformer = new ModelTransformerVersion2(); - var renderer = new MamlRenderer(); - - var markdownModel = parser.ParseString(new string[] { markdown }); - var mamlModel = transformer.NodeModelToMamlModel(markdownModel); - string maml = renderer.MamlModelToString(mamlModel); - - return maml; - } - - private string MarkdownStringToMarkdownString(string markdown, ParserMode parserMode) - { - // Parse - var parser = new MarkdownParser(); - var markdownModel = parser.ParseString(new string[] { markdown }, ParserMode.FormattingPreserve, null); - - // Convert model to Maml - var transformer = new ModelTransformerVersion2(); - var mamlModel = transformer.NodeModelToMamlModel(markdownModel).FirstOrDefault(); - - // Render as markdown - var renderer = new MarkdownV2Renderer(parserMode); - return renderer.MamlModelToString(mamlModel, true); - } - } -} diff --git a/v1/test/Markdown.MAML.Test/Markdown.MAML.Test.csproj b/v1/test/Markdown.MAML.Test/Markdown.MAML.Test.csproj deleted file mode 100644 index 6289a9cd..00000000 --- a/v1/test/Markdown.MAML.Test/Markdown.MAML.Test.csproj +++ /dev/null @@ -1,23 +0,0 @@ -<Project Sdk="Microsoft.NET.Sdk"> - <PropertyGroup> - <TargetFramework>netcoreapp2.0</TargetFramework> - <IsPackable>false</IsPackable> - </PropertyGroup> - <PropertyGroup> - <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <WarningsAsErrors /> - </PropertyGroup> - <ItemGroup> - <PackageReference Include="System.Xml.XPath" Version="4.3.0" /> - <PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" /> - <PackageReference Include="System.Xml.XDocument" Version="4.3.0" /> - <PackageReference Include="System.Xml.XPath.XDocument" Version="4.3.0" /> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.5.0" /> - <PackageReference Include="xunit" Version="2.3.1" /> - <PackageReference Include="xunit.runner.visualstudio" Version="2.3.1" /> - <DotNetCliToolReference Include="dotnet-xunit" Version="2.3.1" /> - </ItemGroup> - <ItemGroup> - <ProjectReference Include="..\..\src\Markdown.MAML\Markdown.MAML.csproj" /> - </ItemGroup> -</Project> diff --git a/v1/test/Markdown.MAML.Test/Parser/ParserTests.cs b/v1/test/Markdown.MAML.Test/Parser/ParserTests.cs deleted file mode 100644 index 9cee66ed..00000000 --- a/v1/test/Markdown.MAML.Test/Parser/ParserTests.cs +++ /dev/null @@ -1,733 +0,0 @@ -using System; -using System.Linq; -using Markdown.MAML.Model; -using Markdown.MAML.Model.Markdown; -using Markdown.MAML.Parser; -using Xunit; -using System.Collections.Generic; - -namespace Markdown.MAML.Test.Parser -{ - public class ParserTests - { - const string headingText = "Heading Text"; - const string codeBlockText = "Code block text\r\non multiple lines"; - const string paragraphText = "Some text\r\non multiple\r\nlines"; - const string hyperlinkText = "Microsoft Corporation"; - const string hyperlinkUri = "https://go.microsoft.com/fwlink/?LinkID=135175&query=stuff"; - - [Fact] - public void ParsesHeadingsWithHashPrefix() - { - - for (int i = 1; i <= 6; i++) - { - HeadingNode headingNode = - this.ParseAndGetExpectedChild<HeadingNode>( - new String('#', i) + headingText + "\r\n", - MarkdownNodeType.Heading); - - Assert.Equal(i, headingNode.HeadingLevel); - Assert.Equal(headingText, headingNode.Text); - } - } - - [Fact] - public void ParsesHeadingsWithUnderlines() - { - string[] headingUnderlines = - { - new String('=', headingText.Length), - new String('-', headingText.Length) - }; - - for (int i = 1; i <= 2; i++) - { - HeadingNode headingNode = - this.ParseAndGetExpectedChild<HeadingNode>( - headingText + "\r\n" + headingUnderlines[i - 1] + "\r\n", - MarkdownNodeType.Heading); - - Assert.Equal(i, headingNode.HeadingLevel); - Assert.Equal(headingText, headingNode.Text); - } - } - - [Fact] - public void ParsesCodeBlock() - { - CodeBlockNode codeBlockNode = - this.ParseAndGetExpectedChild<CodeBlockNode>( - string.Format("```\r\n{0}\r\n```\r\n", codeBlockText), - MarkdownNodeType.CodeBlock); - - Assert.Equal(codeBlockText, codeBlockNode.Text); - } - - - [Fact] - public void ParsesCodeBlockWithLanguageSpecified() - { - CodeBlockNode codeBlockNode = - this.ParseAndGetExpectedChild<CodeBlockNode>( - string.Format("```powershell\r\n{0}\r\n```\r\n", codeBlockText), - MarkdownNodeType.CodeBlock); - - Assert.Equal(codeBlockText, codeBlockNode.Text); - Assert.Equal("powershell", codeBlockNode.LanguageMoniker); - } - - [Fact] - public void ParsesParagraph() - { - ParagraphNode paragraphNode = - this.ParseAndGetExpectedChild<ParagraphNode>( - paragraphText, - MarkdownNodeType.Paragraph); - - Assert.Equal(paragraphText.Replace("\r\n", " "), paragraphNode.Spans.First().Text); - } - - [Fact] - public void ParsesHyperlink() - { - ParagraphNode paragraphNode = - this.ParseAndGetExpectedChild<ParagraphNode>( - string.Format( - "[{0}]({1})", - hyperlinkText, - hyperlinkUri), - MarkdownNodeType.Paragraph); - - HyperlinkSpan hyperlinkSpan = - Assert.IsType<HyperlinkSpan>( - paragraphNode.Spans.FirstOrDefault()); - - Assert.Equal(hyperlinkText, hyperlinkSpan.Text); - Assert.Equal(hyperlinkUri, hyperlinkSpan.Uri); - } - - [Fact] - public void ParsesHyperlinkWithoutLink() - { - ParagraphNode paragraphNode = - this.ParseAndGetExpectedChild<ParagraphNode>( - string.Format( - "[{0}]()", - hyperlinkText), - MarkdownNodeType.Paragraph); - - HyperlinkSpan hyperlinkSpan = - Assert.IsType<HyperlinkSpan>( - paragraphNode.Spans.FirstOrDefault()); - - Assert.Equal(hyperlinkText, hyperlinkSpan.Text); - Assert.Equal("", hyperlinkSpan.Uri); - } - - [Fact] - public void TextSpansCanContainDoubleQuotes() - { - string documentText = @" -# Foo -This is a :""text"" with doublequotes -"; - DocumentNode documentNode = MarkdownStringToDocumentNode(documentText); - var children = documentNode.Children.ToArray(); - Assert.Equal(2, children.Count()); - var spans = Assert.IsType<ParagraphNode>(children[1]).Spans.ToArray(); - Assert.Equal(@"This is a :""text"" with doublequotes", spans[0].Text); - } - - [Fact] - public void TextSpansCanContainBrackets() - { - string documentText = @" -# Foo -about_Hash_Tables (http://go.microsoft.com/fwlink/?LinkID=135175). -"; - DocumentNode documentNode = MarkdownStringToDocumentNode(documentText); - var children = documentNode.Children.ToArray(); - Assert.Equal(2, children.Count()); - var spans = Assert.IsType<ParagraphNode>(children[1]).Spans.ToArray(); - Assert.Equal(@"about_Hash_Tables (http://go.microsoft.com/fwlink/?LinkID=135175).", spans[0].Text); - } - - [Fact] - public void TextSpansCanContainSquareBrackets() - { - string documentText = @" -# Foo -Not a hyperlink [PSObject]. -"; - DocumentNode documentNode = MarkdownStringToDocumentNode(documentText); - var children = documentNode.Children.ToArray(); - Assert.Equal(2, children.Count()); - var spans = Assert.IsType<ParagraphNode>(children[1]).Spans.ToArray(); - Assert.Equal(@"Not a hyperlink [PSObject].", spans[0].Text); - } - - [Fact] - public void ParsesParagraphWithSupportedCharacters() - { - const string allCharacterString = - "This is a \"test\" string; it's very helpful. Success: yes!?"; - - ParagraphNode paragraphNode = - this.ParseAndGetExpectedChild<ParagraphNode>( - allCharacterString, - MarkdownNodeType.Paragraph); - - ParagraphSpan[] spans = paragraphNode.Spans.ToArray(); - - Assert.Equal(allCharacterString, spans[0].Text); - } - - [Fact] - public void ParsesEscapedLessAndMoreCorrectly() - { - const string allCharacterString = - @"\<port-number\>"; - - ParagraphNode paragraphNode = - this.ParseAndGetExpectedChild<ParagraphNode>( - allCharacterString, - MarkdownNodeType.Paragraph); - - ParagraphSpan[] spans = paragraphNode.Spans.ToArray(); - - Assert.Equal("<port-number>", spans[0].Text); - } - - [Fact] - public void ParsesParagraphWithFormattedSpans() - { - ParagraphNode paragraphNode = - this.ParseAndGetExpectedChild<ParagraphNode>( - "Normal\r\n\r\nText *Italic* \r\n\r\n**Bold**\r\n _Italic2_\r\n __Bold2__\r\n### New header!\r\nBoooo\r\n----\r\n", - MarkdownNodeType.Paragraph); - - ParagraphSpan[] spans = paragraphNode.Spans.ToArray(); - - Assert.Equal("Normal\r\nText", spans[0].Text); - Assert.Equal("Italic", spans[1].Text); - Assert.IsType<HardBreakSpan>(spans[2]); - Assert.Equal("Bold", spans[3].Text); - Assert.Equal("Italic2", spans[4].Text); - Assert.Equal("Bold2", spans[5].Text); - } - - [Fact] - public void ParsesDocumentWithMultipleNodes() - { - string documentText = - string.Format( -@" -# {0} - -{2} - -``` -{1} -``` - -## {0} -{2} [{3}]({4}) -", headingText, codeBlockText, paragraphText, hyperlinkText, hyperlinkUri); - - DocumentNode documentNode = MarkdownStringToDocumentNode(documentText); - - HeadingNode headingNode = - this.AssertNodeType<HeadingNode>( - documentNode.Children.ElementAtOrDefault(0), - MarkdownNodeType.Heading); - - Assert.Equal(headingText, headingNode.Text); - Assert.Equal(1, headingNode.HeadingLevel); - - CodeBlockNode codeBlockNode = - this.AssertNodeType<CodeBlockNode>( - documentNode.Children.ElementAtOrDefault(2), - MarkdownNodeType.CodeBlock); - - Assert.Equal(codeBlockText, codeBlockNode.Text); - - headingNode = - this.AssertNodeType<HeadingNode>( - documentNode.Children.ElementAtOrDefault(3), - MarkdownNodeType.Heading); - - Assert.Equal(headingText, headingNode.Text); - Assert.Equal(2, headingNode.HeadingLevel); - - ParagraphNode paragraphNode = - this.AssertNodeType<ParagraphNode>( - documentNode.Children.ElementAtOrDefault(4), - MarkdownNodeType.Paragraph); - - Assert.Equal(paragraphText.Replace("\r\n", " "), paragraphNode.Spans.First().Text); - - HyperlinkSpan hyperlinkSpan = - Assert.IsType<HyperlinkSpan>( - paragraphNode.Spans.ElementAt(1)); - - Assert.Equal(hyperlinkText, hyperlinkSpan.Text); - Assert.Equal(hyperlinkUri, hyperlinkSpan.Uri); - } - - [Fact] - public void CanPaserEmptySourceBlock() - { - DocumentNode documentNode = MarkdownStringToDocumentNode( -@"#### 1: - -```powershell -``` - -```powershell -[Parameter( - ValueFromPipeline = $true, - ParameterSetName = 'Set 1')] -``` -"); - HeadingNode headingNode = - this.AssertNodeType<HeadingNode>( - documentNode.Children.ElementAtOrDefault(0), - MarkdownNodeType.Heading); - - Assert.Equal(4, headingNode.HeadingLevel); - - CodeBlockNode codeBlockNode = - this.AssertNodeType<CodeBlockNode>( - documentNode.Children.ElementAtOrDefault(1), - MarkdownNodeType.CodeBlock); - - Assert.Equal("", codeBlockNode.Text); - } - - [Fact] - public void PreserveLineEndingsInLists() - { - DocumentNode documentNode = MarkdownStringToDocumentNode( -@" --- This is a list --- Yes, with double-dashes --- Because that's how it happens a lot in PS docs - -- This is a regular list -- Item2 -- Item3 - -* Item1 -* Item1 -* Item3 - -And this is not a list. -So it's fine to drop this linebreak. - -New paragraph -"); - ParagraphNode text = - this.AssertNodeType<ParagraphNode>( - documentNode.Children.ElementAtOrDefault(0), - MarkdownNodeType.Paragraph); - - Common.AssertMultilineEqual(@"-- This is a list --- Yes, with double-dashes --- Because that's how it happens a lot in PS docs - -- This is a regular list -- Item2 -- Item3 - -* Item1 -* Item1 -* Item3 - -And this is not a list. So it's fine to drop this linebreak. -New paragraph", text.Spans.First().Text); - } - - [Fact] - public void PreserveLineEndingsInLists2() - { - DocumentNode documentNode = MarkdownStringToDocumentNode( -@" -Valid values are: - --- Block: When the output buffer is full, execution is suspended until the buffer is clear. --- Drop: When the output buffer is full, execution continues. As new output is saved, the oldest output is discarded. --- None: No output buffering mode is specified. The value of the OutputBufferingMode property of the session configuration is used for the disconnected session."); - ParagraphNode text = - this.AssertNodeType<ParagraphNode>( - documentNode.Children.ElementAtOrDefault(0), - MarkdownNodeType.Paragraph); - - Common.AssertMultilineEqual(@"Valid values are: --- Block: When the output buffer is full, execution is suspended until the buffer is clear. --- Drop: When the output buffer is full, execution continues. As new output is saved, the oldest output is discarded. --- None: No output buffering mode is specified. The value of the OutputBufferingMode property of the session configuration is used for the disconnected session.", text.Spans.First().Text); - } - - [Fact] - public void PreserveTextAsIsInFormattingPreserveMode() - { - string text = @"Hello: - - --- Block: aaa. Foo -Bar [this](hyperlink) - --- Drop: <When the> output buffer is full -* None: specified. -It's up - To authors - To format text -"; - DocumentNode documentNode = MarkdownStringToDocumentNodePreserveFormatting(text); - ParagraphNode outText = - this.AssertNodeType<ParagraphNode>( - documentNode.Children.ElementAtOrDefault(0), - MarkdownNodeType.Paragraph); - - Common.AssertMultilineEqual(text, outText.Spans.First().Text); - } - - [Fact] - public void UnderstandsOneLineBreakVsTwoLineBreaks() - { - MarkdownParser markdownParser = new MarkdownParser(); - DocumentNode documentNode = MarkdownStringToDocumentNode(@" -1 -2 - -3 -"); - - - ParagraphNode paragraphNode = - this.AssertNodeType<ParagraphNode>( - documentNode.Children.ElementAtOrDefault(0), - MarkdownNodeType.Paragraph); - - Assert.Equal("1 2\r\n3", paragraphNode.Spans.First().Text); - } - - [Fact] - public void CanUseMultiplyInputStrings() - { - MarkdownParser markdownParser = new MarkdownParser(); - DocumentNode documentNode = - markdownParser.ParseString(new string[] { -@"# Hello -", // TODO: bug: if there is no new-line after header, it fails to parse it. -@"This is new line", -@"```powershell -Code snippet -```" - }); - - - Assert.Equal(3, documentNode.Children.Count()); - - HeadingNode node1 = - this.AssertNodeType<HeadingNode>( - documentNode.Children.ElementAtOrDefault(0), - MarkdownNodeType.Heading); - ParagraphNode node2 = - this.AssertNodeType<ParagraphNode>( - documentNode.Children.ElementAtOrDefault(1), - MarkdownNodeType.Paragraph); - CodeBlockNode node3 = - this.AssertNodeType<CodeBlockNode>( - documentNode.Children.ElementAtOrDefault(2), - MarkdownNodeType.CodeBlock); - } - - [Fact] - public void ParseEscapingSameWayAsGithub() - { - MarkdownParser markdownParser = new MarkdownParser(); - DocumentNode documentNode = MarkdownStringToDocumentNode(@" -\< -\\< -\\\< -\\\\< -\\\\\< -\\\\[ -\ -\\ -\\\ -\\\\ -( -) -[ -] -\( -\) -\[ -\\[ -\] -\` -\* -\\* -\\\* -\_ -\\_ -\\\_ -"); - - - ParagraphNode paragraphNode = - this.AssertNodeType<ParagraphNode>( - documentNode.Children.ElementAtOrDefault(0), - MarkdownNodeType.Paragraph); - - // NOTE: to update this example, create a gist on github to check out how it's parsed. - Assert.Equal(@"< \< \< \\< \\< \\[ \ \ \\ \\ ( ) [ ] ( ) [ \[ ] ` * \* \* _ \_ \_", paragraphNode.Spans.First().Text); - } - - [Fact] - public void GetYamlMetadataWorks() - { - var map = MarkdownParser.GetYamlMetadata(@" - ---- -foo: foo1 - -bar: bar1 ---- - -foo: bar # this is not part of yaml metadata -" -); - Assert.Equal("foo1", map["foo"]); - Assert.Equal("bar1", map["bar"]); - Assert.Equal(2, map.Count); - } - - [Fact] - public void ParsesExample3FromGetPSSnapin() - { - string codeblockText = -@"The first command gets snap-ins that have been added to the current session, including the snap-ins that are installed with Windows PowerShell. In this example, ManagementFeatures is not returned. This indicates that it has not been added to the session. -PS C:\>get-pssnapin - -The second command gets snap-ins that have been registered on your system (including those that have already been added to the session). It does not include the snap-ins that are installed with Windows PowerShell.In this case, the command does not return any snap-ins. This indicates that the ManagementFeatures snapin has not been registered on the system. -PS C:\>get-pssnapin -registered - -The third command creates an alias, ""installutil"", for the path to the InstallUtil tool in .NET Framework. -PS C:\>set-alias installutil $env:windir\Microsoft.NET\Framework\v2.0.50727\installutil.exe - -The fourth command uses the InstallUtil tool to register the snap-in. The command specifies the path to ManagementCmdlets.dll, the file name or ""module name"" of the snap-in. -PS C:\>installutil C:\Dev\Management\ManagementCmdlets.dll - -The fifth command is the same as the second command. This time, you use it to verify that the ManagementCmdlets snap-in is registered. -PS C:\>get-pssnapin -registered - -The sixth command uses the Add-PSSnapin cmdlet to add the ManagementFeatures snap-in to the session. It specifies the name of the snap-in, ManagementFeatures, not the file name. -PS C:\>add-pssnapin ManagementFeatures - -To verify that the snap-in is added to the session, the seventh command uses the Module parameter of the Get-Command cmdlet. It displays the items that were added to the session by a snap-in or module. -PS C:\>get-command -module ManagementFeatures - -You can also use the PSSnapin property of the object that the Get-Command cmdlet returns to find the snap-in or module in which a cmdlet originated. The eighth command uses dot notation to find the value of the PSSnapin property of the Set-Alias cmdlet. -PS C:\>(get-command set-alias).pssnapin"; - string descriptionText = - @"This example demonstrates the process of registering a snap-in on your system and then adding it to your session. It uses ManagementFeatures, a fictitious snap-in implemented in a file called ManagementCmdlets.dll."; - string documentText = string.Format(@" -#### -------------------------- EXAMPLE 3 -------------------------- - -```powershell -{0} - -``` -{1} - - -### RELATED LINKS -[Online Version:](http://go.microsoft.com/fwlink/p/?linkid=289570) -[Get-PSSnapin]() -[Remove-PSSnapin]() -[about_Profiles]() -[about_PSSnapins]() - -## Clear-History - -### SYNOPSIS -Deletes entries from the command history. - -### DESCRIPTION -The Clear-History cmdlet deletes commands from the command history, that is, the list of commands entered during the current session. -Without parameters, Clear-History deletes all commands from the session history, but you can use the parameters of Clear-History to delete selected commands. - -### PARAMETERS - -#### CommandLine [String[]] - -```powershell -[Parameter(ParameterSetName = 'Set 2')] -``` - -Deletes commands with the specified text strings. If you enter more than one string, Clear-History deletes commands with any of the strings. - -", codeblockText, descriptionText); - - DocumentNode documentNode = MarkdownStringToDocumentNode(documentText); - - HeadingNode headingNode = - this.AssertNodeType<HeadingNode>( - documentNode.Children.ElementAtOrDefault(0), - MarkdownNodeType.Heading); - - Assert.Equal(4, headingNode.HeadingLevel); - - CodeBlockNode codeBlockNode = - this.AssertNodeType<CodeBlockNode>( - documentNode.Children.ElementAtOrDefault(1), - MarkdownNodeType.CodeBlock); - - Common.AssertMultilineEqual(codeblockText, codeBlockNode.Text); - - ParagraphNode paragraphNode = - this.AssertNodeType<ParagraphNode>( - documentNode.Children.ElementAtOrDefault(2), - MarkdownNodeType.Paragraph); - Common.AssertMultilineEqual(descriptionText, paragraphNode.Spans.First().Text); - } - - [Fact] - public void PreservesLineBreakAfterHeaderWithHashPrefix() - { - var expectedSynopsis = "This is the synopsis text."; - var expectedDescription = "This is the description text."; - - // Parse markdown - var documentNode = MarkdownStringToDocumentNode($"## SYNOPSIS\r\n{expectedSynopsis}\r\n\r\n## DESCRIPTION\r\n\r\n{expectedDescription}"); - - // Get results - var actualSynopsis = GetParagraph(documentNode, "SYNOPSIS").Spans.FirstOrDefault().Text; - var actualDescription = GetParagraph(documentNode, "DESCRIPTION").Spans.FirstOrDefault().Text; - var synopsisHasLineBreak = GetHeading(documentNode, "SYNOPSIS").FormatOption == SectionFormatOption.LineBreakAfterHeader; - var descriptionHasLineBreak = GetHeading(documentNode, "DESCRIPTION").FormatOption == SectionFormatOption.LineBreakAfterHeader; - - // Check that text matches and line breaks haven't been captured as text - Assert.Equal(expectedSynopsis, actualSynopsis); - Assert.Equal(expectedDescription, actualDescription); - - // Does not use line break and should not be added - Assert.False(synopsisHasLineBreak); - - // Uses line break and should be preserved - Assert.True(descriptionHasLineBreak); - } - - [Fact] - public void PreservesLineBreakAfterParameter() - { - var expectedP1 = "Name parameter description."; - var expectedP2 = "Path parameter description."; - - // Parse markdown - var documentNode = MarkdownStringToDocumentNode($"## PARAMETERS\r\n\r\n### -Name\r\n{expectedP1}\r\n\r\n```yaml\r\n```\r\n\r\n### -Path\r\n\r\n{expectedP2}"); - - var actualP1 = GetParagraph(documentNode, "-Name").Spans.FirstOrDefault().Text; - var actualP2 = GetParagraph(documentNode, "-Path").Spans.FirstOrDefault().Text; - var hasLineBreakP1 = GetHeading(documentNode, "-Name").FormatOption == SectionFormatOption.LineBreakAfterHeader; - var hasLineBreakP2 = GetHeading(documentNode, "-Path").FormatOption == SectionFormatOption.LineBreakAfterHeader; - - // Check that text matches and line breaks haven't been captured as text - Assert.Equal(expectedP1, actualP1); - Assert.Equal(expectedP2, actualP2); - - // Does not use line break and should not be added - Assert.False(hasLineBreakP1); - - // Uses line break and should be preserved - Assert.True(hasLineBreakP2); - } - - [Fact] - public void PreservesLineBreakAfterHeaderWithUnderlines() - { - var expectedSynopsis = "This is the synopsis text."; - var expectedDescription = "This is the description text."; - - // Parse markdown - var documentNode = MarkdownStringToDocumentNode($"SYNOPSIS\r\n---\r\n{expectedSynopsis}\r\n\r\nDESCRIPTION\r\n---\r\n\r\n{expectedDescription}"); - - // Get results - var actualSynopsis = GetParagraph(documentNode, "SYNOPSIS").Spans.FirstOrDefault().Text; - var actualDescription = GetParagraph(documentNode, "DESCRIPTION").Spans.FirstOrDefault().Text; - var synopsisHasLineBreak = GetHeading(documentNode, "SYNOPSIS").FormatOption == SectionFormatOption.LineBreakAfterHeader; - var descriptionHasLineBreak = GetHeading(documentNode, "DESCRIPTION").FormatOption == SectionFormatOption.LineBreakAfterHeader; - - // Check that text matches and line breaks haven't been captured as text - Assert.Equal(expectedSynopsis, actualSynopsis); - Assert.Equal(expectedDescription, actualDescription); - - // Does not use line break and should not be added - Assert.False(synopsisHasLineBreak); - - // Uses line break and should be preserved - Assert.True(descriptionHasLineBreak); - } - - private TNode ParseAndGetExpectedChild<TNode>( - string markdownString, - MarkdownNodeType expectedNodeType) - { - DocumentNode documentNode = MarkdownStringToDocumentNode(markdownString); - return - this.AssertNodeType<TNode>( - documentNode.Children.FirstOrDefault(), - expectedNodeType); - } - - private TNode AssertNodeType<TNode>( - MarkdownNode markdownNode, - MarkdownNodeType expectedNodeType) - { - Assert.NotNull(markdownNode); - Assert.Equal(expectedNodeType, markdownNode.NodeType); - return Assert.IsType<TNode>(markdownNode); - } - - private ParagraphNode GetParagraph(DocumentNode documentNode, string heading) - { - return documentNode - .Children - - // Skip until we reach the heading - .SkipWhile(node => node.NodeType != MarkdownNodeType.Heading || (node as HeadingNode).Text != heading) - - // Get the next paragraph after the heading - .Skip(1) - .OfType<ParagraphNode>() - .FirstOrDefault(); - } - - private HeadingNode GetHeading(DocumentNode documentNode, string text = null) - { - return documentNode - .Children - .OfType<HeadingNode>() - - // If heading was specified, get the specific heading - .FirstOrDefault(node => string.IsNullOrEmpty(text) || node.Text == text); - } - - private DocumentNode MarkdownStringToDocumentNode(string markdown) - { - var parser = new MarkdownParser(); - return parser.ParseString(new string[] { markdown }); - } - - private DocumentNode MarkdownStringToDocumentNodePreserveFormatting(string markdown) - { - var parser = new MarkdownParser(); - return parser.ParseString(new string[] { markdown }, - ParserMode.FormattingPreserve, null); - } - } -} diff --git a/v1/test/Markdown.MAML.Test/Renderer/MamlRendererTests.cs b/v1/test/Markdown.MAML.Test/Renderer/MamlRendererTests.cs deleted file mode 100644 index d3ae5865..00000000 --- a/v1/test/Markdown.MAML.Test/Renderer/MamlRendererTests.cs +++ /dev/null @@ -1,242 +0,0 @@ -using System.Collections.Generic; -using System.Xml; -using System.Xml.XPath; -using Markdown.MAML.Parser; -using Markdown.MAML.Renderer; -using Markdown.MAML.Transformer; -using Xunit; -using Markdown.MAML.Test.EndToEnd; -using Markdown.MAML.Model.MAML; -using Markdown.MAML.Model.Markdown; - -namespace Markdown.MAML.Test.Renderer -{ - public class MamlRendererTests - { - [Fact] - public void RendererProduceNameAndSynopsis() - { - MamlRenderer renderer = new MamlRenderer(); - MamlCommand command = new MamlCommand() - { - Name = "Get-Foo", - Synopsis = new SectionBody("This is the synopsis"), - Description = new SectionBody("This is a long description.") - }; - - command.Parameters.Add(new MamlParameter() - { - Type = "String", - Name = "Name", - Required = true, - Description = "This is the name parameter description.", - VariableLength = true, - Globbing = true, - PipelineInput = "True (ByValue)", - Position = "1", - Aliases = new string []{"GF","Foos","Do"}, - } - ); - command.Parameters.Add(new MamlParameter() - { - Type = "String", - Name = "Path", - Required = true, - Description = "This is the path parameter description.", - VariableLength = true, - Globbing = true, - PipelineInput = "True (ByValue)", - Position = "2", - Aliases = new string[] { }, - } - ); - command.Inputs.Add(new MamlInputOutput() - { - TypeName = "String", - Description = "Input Description goes here!" - - } - ); - command.Outputs.Add(new MamlInputOutput() - { - TypeName = "String", - Description = "Output Description goes here!" - } - ); - command.Examples.Add(new MamlExample() - { - Title = "Example 1", - Code = new[] { new MamlCodeBlock("PS:> Get-Help -YouNeedIt") }, - Remarks = "This does stuff!" - }); - command.Examples.Add(new MamlExample() - { - Title = "Example 2", - Code = new[] { - new MamlCodeBlock("PS:> Get-Help -YouNeedIt", "powershell"), - new MamlCodeBlock("Output")}, - Remarks = "This does stuff!" - }); - command.Links.Add(new MamlLink() - { - LinkName = "PowerShell made by Microsoft Hackathon", - LinkUri = "www.microsoft.com" - } - ); - - string maml = renderer.MamlModelToString(new [] {command}); - - string[] name = EndToEndTests.GetXmlContent(maml, "/msh:helpItems/command:command/command:details/command:name"); - Assert.Single(name); - Assert.Equal("Get-Foo", name[0]); - - string[] synopsis = EndToEndTests.GetXmlContent(maml, "/msh:helpItems/command:command/command:details/maml:description/maml:para"); - Assert.Single(synopsis); - Assert.Equal("This is the synopsis", synopsis[0]); - - string[] description = EndToEndTests.GetXmlContent(maml, "/msh:helpItems/command:command/maml:description/maml:para"); - Assert.Single(description); - Assert.Equal("This is a long description.", description[0]); - - string[] parameter1 = EndToEndTests.GetXmlContent(maml, "/msh:helpItems/command:command/command:parameters/command:parameter[maml:name='Name']/maml:description/maml:para"); - Assert.Single(parameter1); - Assert.Equal("This is the name parameter description.", parameter1[0]); - - string[] parameter2 = EndToEndTests.GetXmlContent(maml, "/msh:helpItems/command:command/command:parameters/command:parameter[maml:name='Path']/maml:description/maml:para"); - Assert.Single(parameter2); - Assert.Equal("This is the path parameter description.", parameter2[0]); - - string[] example1 = EndToEndTests.GetXmlContent(maml, "/msh:helpItems/command:command/command:examples/command:example[contains(maml:title,'Example 1')]/dev:code"); - Assert.Single(example1); - Assert.Equal("PS:> Get-Help -YouNeedIt", example1[0]); - - // Check that multiple code blocks in the same example merge together when rendering maml - string[] example2 = EndToEndTests.GetXmlContent(maml, "/msh:helpItems/command:command/command:examples/command:example[contains(maml:title,'Example 2')]/dev:code"); - Assert.Single(example2); - Common.AssertMultilineEqual("PS:> Get-Help -YouNeedIt\r\n\r\nOutput", example2[0]); - } - - [Fact] - public void RendererProduceSyntaxAndParameter() - { - MamlRenderer renderer = new MamlRenderer(); - MamlCommand command = new MamlCommand() - { - Name = "Get-Foo", - }; - - var param1 = new MamlParameter() - { - Type = "String", - Name = "Param1", - Position = "" - }; - - var param2 = new MamlParameter() - { - Type = "System.Int32", - Name = "Param2", - Position = "Named" - }; - - command.Parameters.Add(param1); - command.Parameters.Add(param2); - - var syntax = new MamlSyntax(); - syntax.Parameters.Add(param1); - syntax.Parameters.Add(param2); - command.Syntax.Add(syntax); - - string maml = renderer.MamlModelToString(new[] { command }); - - string[] syntaxItemName = EndToEndTests.GetXmlContent(maml, "/msh:helpItems/command:command/command:syntax/command:syntaxItem/maml:name"); - Assert.Single(syntaxItemName); - Assert.Equal("Get-Foo", syntaxItemName[0]); - - string[] nameSyntax = EndToEndTests.GetXmlContent(maml, "/msh:helpItems/command:command/command:syntax/command:syntaxItem/command:parameter/maml:name"); - Assert.Equal(2, nameSyntax.Length); - Assert.Equal("Param1", nameSyntax[0]); - Assert.Equal("Param2", nameSyntax[1]); - - string[] nameParam = EndToEndTests.GetXmlContent(maml, "/msh:helpItems/command:command/command:parameters/command:parameter/maml:name"); - Assert.Equal(2, nameParam.Length); - Assert.Equal("Param1", nameParam[0]); - Assert.Equal("Param2", nameParam[1]); - } - - [Fact] - public void RendererProduceEscapeXmlSpecialChars() - { - MamlRenderer renderer = new MamlRenderer(); - MamlCommand command = new MamlCommand() - { - Name = "Get-Foo", - Synopsis = new SectionBody("<port&number>") // < and > should be properly escaped - }; - - string maml = renderer.MamlModelToString(new[] { command }); - - string[] synopsis = EndToEndTests.GetXmlContent(maml, "/msh:helpItems/command:command/command:details/maml:description/maml:para"); - Assert.Single(synopsis); - Assert.Equal(command.Synopsis.Text, synopsis[0]); - } - - [Fact] - public void RendererProducePaddedExampleTitle() - { - MamlRenderer renderer = new MamlRenderer(); - MamlCommand command = new MamlCommand() - { - Name = "Get-Foo", - Synopsis = new SectionBody("This is a description") - }; - - var example1 = new MamlExample() - { - Title = "Example 1", - Code = new[] { new MamlCodeBlock("PS:> Get-Help -YouNeedIt") }, - Remarks = "This does stuff!" - }; - - var example10 = new MamlExample() - { - Title = "Example 10", - Code = new[] { new MamlCodeBlock("PS:> Get-Help -YouNeedIt") }, - Remarks = "This does stuff!" - }; - - var exampleWithTitle = new MamlExample() - { - Title = "Example 11: With a title", - Code = new[] { new MamlCodeBlock("PS:> Get-Help -YouNeedIt") }, - Remarks = "This does stuff!" - }; - - var exampleWithLongTitle = new MamlExample() - { - Title = "Example 12: ".PadRight(66, 'A'), - Code = new[] { new MamlCodeBlock("PS:> Get-Help -YouNeedIt") }, - Remarks = "This does stuff!" - }; - - command.Examples.Add(example1); - command.Examples.Add(example10); - command.Examples.Add(exampleWithTitle); - command.Examples.Add(exampleWithLongTitle); - - string maml = renderer.MamlModelToString(new[] { command }); - - // Check that example header is padded by dashes (-) unless to long - string[] example = EndToEndTests.GetXmlContent(maml, "/msh:helpItems/command:command/command:examples/command:example/maml:title"); - Assert.Equal(4, example.Length); - Assert.Equal(63, example[0].Length); - Assert.Equal(64, example[1].Length); - Assert.Equal(66, example[3].Length); - Assert.Matches($"^-+ {example1.Title} -+$", example[0]); - Assert.Matches($"^-+ {example10.Title} -+$", example[1]); - Assert.Matches($"^-+ {exampleWithTitle.Title} -+$", example[2]); - Assert.Matches($"^{exampleWithLongTitle.Title}$", example[3]); - } - } - -} diff --git a/v1/test/Markdown.MAML.Test/Renderer/MarkdownV2RendererTests.cs b/v1/test/Markdown.MAML.Test/Renderer/MarkdownV2RendererTests.cs deleted file mode 100644 index 9e060567..00000000 --- a/v1/test/Markdown.MAML.Test/Renderer/MarkdownV2RendererTests.cs +++ /dev/null @@ -1,724 +0,0 @@ -using Markdown.MAML.Renderer; -using Markdown.MAML.Model.MAML; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Xunit; -using System.Collections; -using Markdown.MAML.Parser; -using Markdown.MAML.Model.Markdown; - -namespace Markdown.MAML.Test.Renderer -{ - public class MarkdownV2RendererTests - { - [Fact] - public void RendererUsesCorrectEscaping() - { - Assert.Equal(@"\\\<", MarkdownV2Renderer.GetEscapedMarkdownText(@"\<")); - Assert.Equal(@"\\\`", MarkdownV2Renderer.GetEscapedMarkdownText(@"\`")); - Assert.Equal(@"\\\\\<", MarkdownV2Renderer.GetEscapedMarkdownText(@"\\<")); - Assert.Equal(@"\\\\\\\<", MarkdownV2Renderer.GetEscapedMarkdownText(@"\\\<")); - Assert.Equal(@"\", MarkdownV2Renderer.GetEscapedMarkdownText(@"\")); - Assert.Equal(@"\\\\", MarkdownV2Renderer.GetEscapedMarkdownText(@"\\")); - Assert.Equal(@"\\(", MarkdownV2Renderer.GetEscapedMarkdownText(@"\(")); - Assert.Equal(@"(", MarkdownV2Renderer.GetEscapedMarkdownText(@"(")); - Assert.Equal(@")", MarkdownV2Renderer.GetEscapedMarkdownText(@")")); - Assert.Equal(@"\[", MarkdownV2Renderer.GetEscapedMarkdownText(@"[")); - Assert.Equal(@"\]", MarkdownV2Renderer.GetEscapedMarkdownText(@"]")); - Assert.Equal(@"\`", MarkdownV2Renderer.GetEscapedMarkdownText(@"`")); - } - - [Fact] - public void ReturnsSyntaxString() - { - var command = new MamlCommand() - { - Name = "Get-Foo", - SupportCommonParameters = true - }; - - var param1 = new MamlParameter() - { - Name = "Bar", - Type = "BarObject" - }; - - var syntax = new MamlSyntax() - { - IsDefault = true - }; - - syntax.Parameters.Add(param1); - - string syntaxString = MarkdownV2Renderer.GetSyntaxString(command, syntax); - Assert.Equal("Get-Foo [-Bar <BarObject>] [<CommonParameters>]", syntaxString); - } - - [Fact] - public void RendererIgnoresLineBreakWhenBodyIsEmpty() - { - var renderer = new MarkdownV2Renderer(ParserMode.Full); - MamlCommand command = new MamlCommand() - { - Name = "Test-LineBreak", - Notes = new SectionBody("", SectionFormatOption.LineBreakAfterHeader) - }; - - string markdown = renderer.MamlModelToString(command, null); - - Assert.DoesNotContain("\r\n\r\n\r\n", markdown); - } - - [Fact] - public void RendererLineBreakAfterParameter() - { - var renderer = new MarkdownV2Renderer(ParserMode.Full); - - MamlCommand command = new MamlCommand() - { - Name = "Test-LineBreak", - Synopsis = new SectionBody("This is the synopsis"), - Description = new SectionBody("This is a long description"), - Notes = new SectionBody("This is a note") - }; - - var parameter1 = new MamlParameter() - { - Type = "String", - Name = "Name", - Required = true, - Description = "Name description.", - Globbing = true - }; - - var parameter2 = new MamlParameter() - { - Type = "String", - Name = "Path", - FormatOption = SectionFormatOption.LineBreakAfterHeader, - Required = true, - Description = "Path description.", - Globbing = true - }; - - command.Parameters.Add(parameter1); - command.Parameters.Add(parameter2); - - var syntax1 = new MamlSyntax() - { - ParameterSetName = "ByName" - }; - - syntax1.Parameters.Add(parameter1); - syntax1.Parameters.Add(parameter2); - command.Syntax.Add(syntax1); - - string markdown = renderer.MamlModelToString(command, null); - - // Does not use line break and should not be added - Assert.Contains("### -Name\r\nName description.", markdown); - - // Uses line break and should be preserved - Assert.Contains("### -Path\r\n\r\nPath description.", markdown); - } - - [Fact] - public void RendererLineBreakAfterParameterForUpdate() - { - var renderer = new MarkdownV2Renderer(ParserMode.FormattingPreserve); - - MamlCommand command = new MamlCommand() - { - Name = "Test-LineBreak", - Synopsis = new SectionBody("This is the synopsis"), - Description = new SectionBody("This is a long description"), - Notes = new SectionBody("This is a note") - }; - - var parameter1 = new MamlParameter() - { - Type = "String", - Name = "Name", - Required = true, - Description = "Name description.", - Globbing = true - }; - - var parameter2 = new MamlParameter() - { - Type = "String", - Name = "Path", - FormatOption = SectionFormatOption.LineBreakAfterHeader, - Required = true, - Description = "Path description.", - Globbing = true - }; - - command.Parameters.Add(parameter1); - command.Parameters.Add(parameter2); - - var syntax1 = new MamlSyntax() - { - ParameterSetName = "ByName" - }; - - syntax1.Parameters.Add(parameter1); - syntax1.Parameters.Add(parameter2); - command.Syntax.Add(syntax1); - - string markdown = renderer.MamlModelToString(command, null); - - // Does not use line break and should not be added - Assert.Contains("### -Name\r\nName description.\r\n\r\n```yaml", markdown); - - // Uses line break and should be preserved - Assert.Contains("### -Path\r\n\r\nPath description.\r\n\r\n```yaml", markdown); - } - - [Fact] - public void RendersExamplesFromMaml() - { - var renderer = new MarkdownV2Renderer(ParserMode.Full); - - MamlCommand command = new MamlCommand() - { - Name = "Test-LineBreak", - }; - - var example1 = new MamlExample() - { - Title = "Example 1", - Code = new[] { new MamlCodeBlock("PS C:\\> Get-Help") }, - Remarks = "This is an example to get help." - }; - - var example2 = new MamlExample() - { - Title = "Example 2", - Code = new[] { new MamlCodeBlock("PS C:\\> Get-Help -Full") }, - Introduction = "Intro" - }; - - var example3 = new MamlExample() - { - Title = "Example 3", - FormatOption = SectionFormatOption.LineBreakAfterHeader, - Code = new[] { new MamlCodeBlock("PS C:\\> Get-Help", "powershell") }, - Remarks = "This is an example to get help." - }; - - var example4 = new MamlExample() - { - Title = "Example 4", - FormatOption = SectionFormatOption.LineBreakAfterHeader, - Code = new[] { new MamlCodeBlock("PS C:\\> Get-Help -Full") }, - Introduction = "Intro" - }; - - var example5 = new MamlExample() - { - Title = "---Example 5---", - Code = new[] { new MamlCodeBlock("PS C:\\> Get-Help -Full") }, - Introduction = "With some dashes and no spaces" - }; - - var example6 = new MamlExample() - { - Title = "------------------ Example 6: With extra info ------------------", - Code = new[] { new MamlCodeBlock("PS C:\\> Get-Help -Full") }, - Introduction = "Padded to 64 characters and spaces" - }; - - var example7 = new MamlExample() - { - Title = "Example 7: ".PadRight(66, 'A'), - Code = new[] { new MamlCodeBlock("PS C:\\> Get-Help -Full") }, - Introduction = "Greater then 64 characters" - }; - - command.Examples.Add(example1); - command.Examples.Add(example2); - command.Examples.Add(example3); - command.Examples.Add(example4); - command.Examples.Add(example5); - command.Examples.Add(example6); - command.Examples.Add(example7); - - string markdown = renderer.MamlModelToString(command, null); - - // Does not use line break and should not be added - Assert.Contains("### Example 1\r\n```", markdown); - Assert.Contains("### Example 2\r\nIntro\r\n\r\n```", markdown); - - // Uses line break and should be preserved - Assert.Contains("### Example 3\r\n\r\n```powershell", markdown); - Assert.Contains("### Example 4\r\n\r\nIntro\r\n\r\n```", markdown); - - // Includes title padding that should be removed - Assert.Contains("### Example 5\r\n", markdown); - Assert.Contains("### Example 6: With extra info\r\n", markdown); - Assert.Contains($"### {example7.Title}\r\n", markdown); - } - - [Fact] - public void RendererCreatesWorkflowParametersEntry() - { - var renderer = new MarkdownV2Renderer(ParserMode.Full); - MamlCommand command = new MamlCommand() - { - Name = "Workflow", - IsWorkflow = true - }; - - command.Syntax.Add(new MamlSyntax()); - - string markdown = renderer.MamlModelToString(command, null); - Common.AssertMultilineEqual(@"--- -schema: 2.0.0 ---- - -# Workflow - -## SYNOPSIS - -## SYNTAX - -``` -Workflow [<WorkflowCommonParameters>] [<CommonParameters>] -``` - -## DESCRIPTION - -## EXAMPLES - -## PARAMETERS - -### WorkflowCommonParameters -This cmdlet supports the following workflow common parameters: -PSParameterCollection, -PSComputerName, -PSCredential, -PSConnectionRetryCount, -PSConnectionRetryIntervalSec, -PSRunningTimeoutSec, -PSElapsedTimeoutSec, -PSPersist, -PSAuthentication, -PSAuthenticationLevel, -PSApplicationName, -PSPort, -PSUseSSL, -PSConfigurationName, -PSConnectionURI, -PSAllowRedirection, -PSSessionOption, -PSCertificateThumbprint, -PSPrivateMetadata, -AsJob, -JobName, and -InputObject. For more information, see [about_WorkflowCommonParameters](http://go.microsoft.com/fwlink/p/?LinkID=533952). - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -## OUTPUTS - -## NOTES - -## RELATED LINKS -", markdown); - } - - [Fact] - public void RendererNormalizeQuotesAndDashes() - { - var renderer = new MarkdownV2Renderer(ParserMode.Full); - MamlCommand command = new MamlCommand() - { - Name = "Test-Quotes", - Description = new SectionBody(@"”“‘’––-") - }; - - string markdown = renderer.MamlModelToString(command, null); - Common.AssertMultilineEqual(@"--- -schema: 2.0.0 ---- - -# Test-Quotes - -## SYNOPSIS - -## SYNTAX - -## DESCRIPTION -""""''--- - -## EXAMPLES - -## PARAMETERS - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -## OUTPUTS - -## NOTES - -## RELATED LINKS -", markdown); - } - - [Fact] - public void RendererProduceMarkdownV2Output() - { - var renderer = new MarkdownV2Renderer(ParserMode.Full); - MamlCommand command = new MamlCommand() - { - Name = "Get-Foo", - Synopsis = new SectionBody("This is the synopsis"), - Description = new SectionBody("This is a long description.\r\nWith two paragraphs. And the second one contains of few line! They should be auto-wrapped. Because, why not? We can do that kind of the things, no problem.\r\n\r\n-- Foo. Bar.\r\n-- Don't break. The list.\r\n-- Into. Pieces"), - Notes = new SectionBody("This is a multiline note.\r\nSecond line.") - }; - - var parameter = new MamlParameter() - { - Type = "String", - Name = "Name", - Required = true, - Description = "Parameter Description.", - VariableLength = true, - Globbing = true, - PipelineInput = "True (ByValue)", - Position = "1", - DefaultValue = "trololo", - Aliases = new string[] { "GF", "Foos", "Do" }, - Applicable = new string[] { "Module1", "Module2" } - }; - parameter.ParameterValueGroup.AddRange(new string[] { "Value1", "Value2" }); - - command.Parameters.Add(parameter); - - var syntax1 = new MamlSyntax() - { - ParameterSetName = "ByName" - }; - syntax1.Parameters.Add(parameter); - command.Syntax.Add(syntax1); - - command.Inputs.Add(new MamlInputOutput() - { - TypeName = "String", - Description = "Input <Description> goes here!" - }); - command.Outputs.Add(new MamlInputOutput() - { - TypeName = "String", - Description = "Output Description goes here!" - }); - command.Examples.Add(new MamlExample() - { - Title = "Example 1", - Code = new[] { new MamlCodeBlock("PS:> Get-Help -YouNeedIt") }, - Remarks = "This does stuff!" - }); - command.Examples.Add(new MamlExample() - { - Title = "Example 2", - Code = new[] { new MamlCodeBlock("PS:> Get-Help -YouNeedTwo") }, - }); - command.Examples.Add(new MamlExample() - { - Title = "Example 3", - Code = new[] { new MamlCodeBlock("PS:> Get-Help -YouNeedTwo") }, - }); - command.Links.Add(new MamlLink() - { - LinkName = "PowerShell made by Microsoft Hackathon", - LinkUri = "www.microsoft.com" - - }); - - command.Links.Add(new MamlLink() - { - LinkName = "", // if name is empty, it would be populated with uri - LinkUri = "http://foo.com" - - }); - - // Note that the metadata should end up getting alphabetized. - var metadata = new Hashtable(); - metadata["foo"] = "bar"; - metadata["null"] = null; - string markdown = renderer.MamlModelToString(command, metadata); - Common.AssertMultilineEqual(@"--- -foo: bar -null: -schema: 2.0.0 ---- - -# Get-Foo - -## SYNOPSIS -This is the synopsis - -## SYNTAX - -``` -Get-Foo [-Name] <String> [<CommonParameters>] -``` - -## DESCRIPTION -This is a long description. - -With two paragraphs. -And the second one contains of few line! -They should be auto-wrapped. -Because, why not? -We can do that kind of the things, no problem. - --- Foo. Bar. --- Don't break. The list. --- Into. Pieces - -## EXAMPLES - -### Example 1 -``` -PS:> Get-Help -YouNeedIt -``` - -This does stuff! - -### Example 2 -``` -PS:> Get-Help -YouNeedTwo -``` - -### Example 3 -``` -PS:> Get-Help -YouNeedTwo -``` - -## PARAMETERS - -### -Name -Parameter Description. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: GF, Foos, Do -Accepted values: Value1, Value2 -Applicable: Module1, Module2 - -Required: True -Position: 1 -Default value: trololo -Accept pipeline input: True (ByValue) -Accept wildcard characters: True -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### String -Input \<Description\> goes here! - -## OUTPUTS - -### String -Output Description goes here! - -## NOTES -This is a multiline note. - -Second line. - -## RELATED LINKS - -[PowerShell made by Microsoft Hackathon](www.microsoft.com) - -[http://foo.com](http://foo.com) - -", markdown); - } - - [Fact] - public void RenderesAllParameterSetMoniker() - { - var renderer = new MarkdownV2Renderer(ParserMode.Full); - MamlCommand command = new MamlCommand() - { - Name = "Get-Foo", - }; - - var commonParam = new MamlParameter() - { - Type = "String", - Name = "Common", - Required = true - }; - - var parameter1 = new MamlParameter() - { - Type = "String", - Name = "First", - Required = true - }; - - var parameter2 = new MamlParameter() - { - Type = "String", - Name = "Second", - Required = true - }; - - command.Parameters.Add(commonParam); - command.Parameters.Add(parameter1); - command.Parameters.Add(parameter2); - - var syntax1 = new MamlSyntax() - { - ParameterSetName = "FirstSyntax" - }; - - syntax1.Parameters.Add(commonParam); - syntax1.Parameters.Add(parameter1); - - var syntax2 = new MamlSyntax() - { - ParameterSetName = "SecondSyntax", - IsDefault = true - }; - - syntax2.Parameters.Add(commonParam); - syntax2.Parameters.Add(parameter2); - - command.Syntax.Add(syntax1); - command.Syntax.Add(syntax2); - - string markdown = renderer.MamlModelToString(command, null); - Common.AssertMultilineEqual(@"--- -schema: 2.0.0 ---- - -# Get-Foo - -## SYNOPSIS - -## SYNTAX - -### FirstSyntax -``` -Get-Foo -Common <String> -First <String> [<CommonParameters>] -``` - -### SecondSyntax (Default) -``` -Get-Foo -Common <String> -Second <String> [<CommonParameters>] -``` - -## DESCRIPTION - -## EXAMPLES - -## PARAMETERS - -### -Common -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: True -Position: Named -Default value: None -Accept pipeline input: false -Accept wildcard characters: False -``` - -### -First -```yaml -Type: String -Parameter Sets: FirstSyntax -Aliases: - -Required: True -Position: Named -Default value: None -Accept pipeline input: false -Accept wildcard characters: False -``` - -### -Second -```yaml -Type: String -Parameter Sets: SecondSyntax -Aliases: - -Required: True -Position: Named -Default value: None -Accept pipeline input: false -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -## OUTPUTS - -## NOTES - -## RELATED LINKS -", markdown); - } - - [Fact] - public void RenderesWithPreservedFormatting() - { - var renderer = new MarkdownV2Renderer(ParserMode.FormattingPreserve); - MamlCommand command = new MamlCommand() - { - Name = "Get-Foo", - SupportCommonParameters = false, - Description = new SectionBody(@"Hello -This \<description \> should be preserved by renderer -With all [hyper](https://links.com) and yada - -- yada - -* Also -* This list. May look. A little -weired -* [ ] But - -* [ ] It should be left" - )}; - - command.Links.Add( - new MamlLink(isSimplifiedTextLink: true) - { - LinkName = "Any text [can](go here)\r\n[any](text)" - } - ); - - string markdown = renderer.MamlModelToString(command, null); - Common.AssertMultilineEqual(@"--- -schema: 2.0.0 ---- - -# Get-Foo - -## SYNOPSIS - -## SYNTAX - -## DESCRIPTION -" + command.Description + @" - -## EXAMPLES - -## PARAMETERS - -## INPUTS - -## OUTPUTS - -## NOTES - -## RELATED LINKS - -Any text [can](go here) -[any](text)", markdown); - } - } -} diff --git a/v1/test/Markdown.MAML.Test/Renderer/TextRendererTests.cs b/v1/test/Markdown.MAML.Test/Renderer/TextRendererTests.cs deleted file mode 100644 index 89ea81cb..00000000 --- a/v1/test/Markdown.MAML.Test/Renderer/TextRendererTests.cs +++ /dev/null @@ -1,424 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Xunit; -using Markdown.MAML.Model.Markdown; -using Markdown.MAML.Parser; -using Markdown.MAML.Renderer; - -namespace Markdown.MAML.Test.Renderer -{ - public class TextRendererTests - { - [Fact] - public void RendererCreatesAboutTopicString() - { - var renderer = new TextRenderer(80); - MarkdownParser parser = new MarkdownParser(); - string markdown = @"# TopicName -## about_TopicName - -``` -ABOUT TOPIC NOTE: -The first header of the about topic should be the topic name. -The second header contains the lookup name used by the help system. - -IE: -# Some Help Topic Name -## SomeHelpTopicFileName - -This will be transformed into the text file as `about_SomeHelpTopicFileName`. - -Do not include file extensions. -The second header should have no spaces. -``` - -# SHORT DESCRIPTION -{{Short Description Placeholder}} - -``` -ABOUT TOPIC NOTE: -About topics can be no longer than 80 characters wide when rendered to text. -Any topics greater than 80 characters will be automatically wrapped. -The generated about topic will be encoded UTF-8. -``` - -# LONG DESCRIPTION -{{Long Description Placeholder}} - -## Optional Subtopics -{{Optional Subtopic Placeholder}} - -# EXAMPLES -{{Code or descriptive examples of how to leverage functions described.}} - -# NOTE -{{Note Placeholder - Additional information that a user needs to know.}} - -# TROUBLESHOOTING NOTE -{{Troubleshooting Placeholder - Warns users of bug.}} - -{{Explains behavior that is likely to change with fixes}} - -# SEE ALSO -{{See also placeholder, list related articles, blogs, and video URLs.}} - -- https://somewebsite.com - -# KEYWORDS -{{List alternate names or titles for this topic that readers might use.}} - -- {{Keyword Placeholder}} -- {{Keyword Placeholder}} -- {{Keyword Placeholder}} -- {{Keyword Placeholder}} -"; - DocumentNode document = parser.ParseString(new string[] { markdown }); - - string content = renderer.AboutMarkdownToString(document); - - string expectedOut = @"TOPIC - about_topicname - - ABOUT TOPIC NOTE: - The first header of the about topic should be the topic name. - The second header contains the lookup name used by the help system. - - IE: - # Some Help Topic Name - ## SomeHelpTopicFileName - - This will be transformed into the text file as `about_SomeHelpTopicFileName`. - - Do not include file extensions. - The second header should have no spaces. - -SHORT DESCRIPTION - {{Short Description Placeholder}} - - ABOUT TOPIC NOTE: - About topics can be no longer than 80 characters wide when rendered to text. - Any topics greater than 80 characters will be automatically wrapped. - The generated about topic will be encoded UTF-8. - -LONG DESCRIPTION - {{Long Description Placeholder}} - -Optional Subtopics - {{Optional Subtopic Placeholder}} - -EXAMPLES - {{Code or descriptive examples of how to leverage functions described.}} - -NOTE - {{Note Placeholder - Additional information that a user needs to know.}} - -TROUBLESHOOTING NOTE - {{Troubleshooting Placeholder - Warns users of bug.}} - {{Explains behavior that is likely to change with fixes}} - -SEE ALSO - {{See also placeholder, list related articles, blogs, and video URLs.}} - - https://somewebsite.com - -KEYWORDS - {{List alternate names or titles for this topic that readers might use.}} - - {{Keyword Placeholder}} - - {{Keyword Placeholder}} - - {{Keyword Placeholder}} - - {{Keyword Placeholder}} - -"; - Common.AssertMultilineEqual(expectedOut, content); - } - - - [Fact] - public void RendererSuccessfullParsesMultiLineAboutContent() - { - var renderer = new TextRenderer(80); - MarkdownParser parser = new MarkdownParser(); - string markdown = @"# About Throw -## about_Throw - -# SHORT DESCRIPTION - -Describes the Throw keyword, which generates a terminating error. - -# LONG DESCRIPTION -The Throw keyword causes a terminating error. You can use the Throw keyword -to stop the processing of a command, function, or script. - -For example, you can use the Throw keyword in the script block of an If -statement to respond to a condition or in the Catch block of a -Try-Catch-Finally statement. You can also use the Throw keyword in a -parameter declaration to make a function parameter mandatory. - -The Throw keyword can throw any object, such as a user message string or -the object that caused the error. - - -## SYNTAX - -The syntax of the Throw keyword is as follows: - -``` -throw [<expression>] -``` - - -The expression in the Throw syntax is optional. When the Throw statement -does not appear in a Catch block, and it does not include an expression, -it generates a ScriptHalted error. - -``` -C:\PS> throw - -ScriptHalted -At line:1 char:6 -+ throw <<<< - + CategoryInfo : OperationStopped: (:) [], RuntimeException - + FullyQualifiedErrorId : ScriptHalted -``` - -If the Throw keyword is used in a Catch block without an expression, it -throws the current RuntimeException again. For more information, see -about_Try_Catch_Finally. - - -## THROWING A STRING - -The optional expression in a Throw statement can be a string, as shown in -the following example: - -``` -C:\PS> throw 'This is an error.' - -This is an error. -At line:1 char:6 -+ throw <<<< 'This is an error.' - + CategoryInfo : OperationStopped: (This is an error.:String) [], RuntimeException - + FullyQualifiedErrorId : This is an error. -``` - -## THROWING OTHER OBJECTS - -The expression can also be an object that throws the object that represents -the PowerShell process, as shown in the following example: - -``` -C:\PS> throw (get-process PowerShell) - -System.Diagnostics.Process (PowerShell) -At line:1 char:6 -+ throw <<<< (get-process PowerShell) - + CategoryInfo : OperationStopped: (System.Diagnostics.Process (PowerShell):Process) [ -RuntimeException - + FullyQualifiedErrorId : System.Diagnostics.Process(PowerShell) -``` - -You can use the TargetObject property of the ErrorRecord object in the -$error automatic variable to examine the error. - -``` -C:\PS> $error[0].targetobject - -Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName - -------- ------ ----- ----- ----- ------ -- ----------- - - 319 26 61016 70864 568 3.28 5548 PowerShell -``` - -You can also throw an ErrorRecord object or a Microsoft.NET Framework -exception. The following example uses the Throw keyword to throw a -System.FormatException object. - -``` -C:\PS> $formatError = new- object system.formatexception - -C:\PS> throw $formatError - -One of the identified items was in an invalid format. -At line:1 char:6 -+ throw <<<< $formatError - + CategoryInfo : OperationStopped: (:) [], FormatException - + FullyQualifiedErrorId : One of the identified items was in an invalid format. -``` - -## RESULTING ERROR - -The Throw keyword can generate an ErrorRecord object. The Exception -property of the ErrorRecord object contains a RuntimeException object. -The remainder of the ErrorRecord object and the RuntimeException object -vary with the object that the Throw keyword throws. - -The RunTimeException object is wrapped in an ErrorRecord object, and the -ErrorRecord object is automatically saved in the $Error automatic variable. - - -## USING THROW TO CREATE A MANDATORY PARAMETER - -You can use the Throw keyword to make a function parameter mandatory. - -This is an alternative to using the Mandatory parameter of the Parameter -keyword.When you use the Mandatory parameter, the system prompts the user -for the required parameter value. When you use the Throw keyword, the -command stops and displays the error record. - -For example, the Throw keyword in the parameter subexpression makes the -Path parameter a required parameter in the function. - -In this case, the Throw keyword throws a message string, but it is the -presence of the Throw keyword that generates the terminating error if -the Path parameter is not specified. The expression that follows Throw -is optional. - -``` -function Get-XMLFiles -{ - param($path = $(throw 'The Path parameter is required.')) - dir - path $path\*.xml - recurse | sort lastwritetime | ft lastwritetime, attributes, name - auto -} -``` - -# SEE ALSO - -- about_Break -- about_Continue -- about_Scope -- about_Trap -- about_Try_Catch_Finally -"; - DocumentNode document = parser.ParseString(new string[] { markdown }); - - string content = renderer.AboutMarkdownToString(document); - - string expectedOut = @"TOPIC - about_throw - -SHORT DESCRIPTION - Describes the Throw keyword, which generates a terminating error. - -LONG DESCRIPTION - The Throw keyword causes a terminating error. You can use the Throw keyword - to stop the processing of a command, function, or script. - For example, you can use the Throw keyword in the script block of an If - statement to respond to a condition or in the Catch block of a - Try-Catch-Finally statement. You can also use the Throw keyword in a - parameter declaration to make a function parameter mandatory. - The Throw keyword can throw any object, such as a user message string or the - object that caused the error. - -SYNTAX - The syntax of the Throw keyword is as follows: - - throw [<expression>] - - The expression in the Throw syntax is optional. When the Throw statement - does not appear in a Catch block, and it does not include an expression, it - generates a ScriptHalted error. - - C:\PS> throw - - ScriptHalted - At line:1 char:6 - + throw <<<< - + CategoryInfo : OperationStopped: (:) [], RuntimeException - + FullyQualifiedErrorId : ScriptHalted - - If the Throw keyword is used in a Catch block without an expression, it - throws the current RuntimeException again. For more information, see - about_Try_Catch_Finally. - -THROWING A STRING - The optional expression in a Throw statement can be a string, as shown in - the following example: - - C:\PS> throw 'This is an error.' - - This is an error. - At line:1 char:6 - + throw <<<< 'This is an error.' - + CategoryInfo : OperationStopped: (This is an error.:String) [], RuntimeException - + FullyQualifiedErrorId : This is an error. - -THROWING OTHER OBJECTS - The expression can also be an object that throws the object that represents - the PowerShell process, as shown in the following example: - - C:\PS> throw (get-process PowerShell) - - System.Diagnostics.Process (PowerShell) - At line:1 char:6 - + throw <<<< (get-process PowerShell) - + CategoryInfo : OperationStopped: (System.Diagnostics.Process (PowerShell):Process) [ - RuntimeException - + FullyQualifiedErrorId : System.Diagnostics.Process(PowerShell) - - You can use the TargetObject property of the ErrorRecord object in the - $error automatic variable to examine the error. - - C:\PS> $error[0].targetobject - - Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName - - ------- ------ ----- ----- ----- ------ -- ----------- - - 319 26 61016 70864 568 3.28 5548 PowerShell - - You can also throw an ErrorRecord object or a Microsoft.NET Framework - exception. The following example uses the Throw keyword to throw a - System.FormatException object. - - C:\PS> $formatError = new- object system.formatexception - - C:\PS> throw $formatError - - One of the identified items was in an invalid format. - At line:1 char:6 - + throw <<<< $formatError - + CategoryInfo : OperationStopped: (:) [], FormatException - + FullyQualifiedErrorId : One of the identified items was in an invalid format. - -RESULTING ERROR - The Throw keyword can generate an ErrorRecord object. The Exception property - of the ErrorRecord object contains a RuntimeException object. The remainder - of the ErrorRecord object and the RuntimeException object vary with the - object that the Throw keyword throws. - The RunTimeException object is wrapped in an ErrorRecord object, and the - ErrorRecord object is automatically saved in the $Error automatic variable. - -USING THROW TO CREATE A MANDATORY PARAMETER - You can use the Throw keyword to make a function parameter mandatory. - This is an alternative to using the Mandatory parameter of the Parameter - keyword.When you use the Mandatory parameter, the system prompts the user - for the required parameter value. When you use the Throw keyword, the - command stops and displays the error record. - For example, the Throw keyword in the parameter subexpression makes the Path - parameter a required parameter in the function. - In this case, the Throw keyword throws a message string, but it is the - presence of the Throw keyword that generates the terminating error if the - Path parameter is not specified. The expression that follows Throw is - optional. - - function Get-XMLFiles - { - param($path = $(throw 'The Path parameter is required.')) - dir - path $path\*.xml - recurse | sort lastwritetime | ft lastwritetime, attributes, name - auto - } - -SEE ALSO - - about_Break - - about_Continue - - about_Scope - - about_Trap - - about_Try_Catch_Finally - -"; - Common.AssertMultilineEqual(expectedOut, content); - } - } -} diff --git a/v1/test/Markdown.MAML.Test/Renderer/YamlRendererTests.cs b/v1/test/Markdown.MAML.Test/Renderer/YamlRendererTests.cs deleted file mode 100644 index 6f2f081a..00000000 --- a/v1/test/Markdown.MAML.Test/Renderer/YamlRendererTests.cs +++ /dev/null @@ -1,290 +0,0 @@ -using Markdown.MAML.Model.MAML; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Markdown.MAML.Model.YAML; -using Markdown.MAML.Renderer; -using Xunit; -using YamlDotNet.Serialization; -using YamlDotNet.Serialization.NamingConventions; -using Markdown.MAML.Model.Markdown; - -namespace Markdown.MAML.Test.Renderer -{ - public class YamlRendererTests - { - [Fact] - public void RendererProducesNameAndTextFields() - { - var model = CreateModel(); - - var output = YamlRenderer.MamlModelToString(model); - - var deserializer = CreateDeserializer(); - - var writtenModel = deserializer.Deserialize<YamlCommand>(output); - - Assert.NotNull(writtenModel); - Assert.Equal(model.Name, writtenModel.Name); - Assert.Equal(model.Description.Text, writtenModel.Remarks); - Assert.Equal(model.Synopsis.Text, writtenModel.Summary); - Assert.Equal(model.Notes.Text, writtenModel.Notes); - } - - [Fact] - public void RenderProducesExamples() - { - var model = CreateModel(); - - var output = YamlRenderer.MamlModelToString(model); - - var deserializer = CreateDeserializer(); - - var writtenModel = deserializer.Deserialize<YamlCommand>(output); - - Assert.Single(writtenModel.Examples); - - var example = writtenModel.Examples.Single(); - - Assert.Equal(model.Examples.Single().Introduction, example.PreCode); - Assert.Equal(model.Examples.Single().Code.Single().Text, example.Code); - Assert.Equal(model.Examples.Single().Remarks, example.PostCode); - Assert.Equal(model.Examples.Single().Title, example.Name); - } - - [Fact] - public void RenderProducesInputs() - { - var model = CreateModel(); - - var output = YamlRenderer.MamlModelToString(model); - - var deserializer = CreateDeserializer(); - - var writtenModel = deserializer.Deserialize<YamlCommand>(output); - - Assert.Single(writtenModel.Inputs); - - var input = writtenModel.Inputs.Single(); - - Assert.Equal(model.Inputs.Single().Description, input.Description); - Assert.Equal(model.Inputs.Single().TypeName, input.Type); - } - - [Fact] - public void RenderProducesLinks() - { - var model = CreateModel(); - - var output = YamlRenderer.MamlModelToString(model); - - var deserializer = CreateDeserializer(); - - var writtenModel = deserializer.Deserialize<YamlCommand>(output); - - Assert.Single(writtenModel.Links); - - var link = writtenModel.Links.Single(); - - Assert.Equal(model.Links.Single().LinkName, link.Text); - Assert.Equal(model.Links.Single().LinkUri, link.Href); - } - - [Fact] - public void RenderProducesModule() - { - var model = CreateModel(); - - var output = YamlRenderer.MamlModelToString(model); - - var deserializer = CreateDeserializer(); - - var writtenModel = deserializer.Deserialize<YamlCommand>(output); - - Assert.NotNull(writtenModel.Module); - - Assert.Equal(model.ModuleName, writtenModel.Module.Name); - } - - [Fact] - public void RenderProducesOptionalParameters() - { - var model = CreateModel(); - - var output = YamlRenderer.MamlModelToString(model); - - var deserializer = CreateDeserializer(); - - var writtenModel = deserializer.Deserialize<YamlCommand>(output); - - Assert.Single(writtenModel.OptionalParameters); - - var optionalParameter = writtenModel.OptionalParameters.Single(); - var expectedParameter = model.Parameters.Single(p => !p.Required); - - Assert.Equal(expectedParameter.Globbing, optionalParameter.AcceptWildcardCharacters); - Assert.Equal(expectedParameter.Aliases, optionalParameter.Aliases); - Assert.Equal(expectedParameter.DefaultValue, optionalParameter.DefaultValue); - Assert.Equal(expectedParameter.Description, optionalParameter.Description); - Assert.Equal(expectedParameter.Name, optionalParameter.Name); - Assert.Equal(expectedParameter.ParameterValueGroup, optionalParameter.ParameterValueGroup); - Assert.Equal(expectedParameter.PipelineInput, optionalParameter.PipelineInput); - Assert.Equal(expectedParameter.Position, optionalParameter.Position); - Assert.Equal(expectedParameter.Type, optionalParameter.Type); - } - - [Fact] - public void RenderProducesOutputs() - { - var model = CreateModel(); - - var output = YamlRenderer.MamlModelToString(model); - - var deserializer = CreateDeserializer(); - - var writtenModel = deserializer.Deserialize<YamlCommand>(output); - - Assert.Single(writtenModel.Outputs); - - var outputItem = writtenModel.Outputs.Single(); - - Assert.Equal(model.Outputs.Single().TypeName, outputItem.Type); - Assert.Equal(model.Outputs.Single().Description, outputItem.Description); - } - - [Fact] - public void RenderProducesRequiredParameters() - { - var model = CreateModel(); - - var output = YamlRenderer.MamlModelToString(model); - - var deserializer = CreateDeserializer(); - - var writtenModel = deserializer.Deserialize<YamlCommand>(output); - - Assert.Single(writtenModel.RequiredParameters); - - var requiredParameter = writtenModel.RequiredParameters.Single(); - var expectedParameter = model.Parameters.Single(p => p.Required); - - Assert.Equal(expectedParameter.Globbing, requiredParameter.AcceptWildcardCharacters); - Assert.Equal(expectedParameter.Aliases, requiredParameter.Aliases); - Assert.Equal(expectedParameter.DefaultValue, requiredParameter.DefaultValue); - Assert.Equal(expectedParameter.Description, requiredParameter.Description); - Assert.Equal(expectedParameter.Name, requiredParameter.Name); - Assert.Equal(expectedParameter.ParameterValueGroup, requiredParameter.ParameterValueGroup); - Assert.Equal(expectedParameter.PipelineInput, requiredParameter.PipelineInput); - Assert.Equal(expectedParameter.Position, requiredParameter.Position); - Assert.Equal(expectedParameter.Type, requiredParameter.Type); - } - - [Fact] - public void RenderProducesSyntaxes() - { - var model = CreateModel(); - - var output = YamlRenderer.MamlModelToString(model); - - var deserializer = CreateDeserializer(); - - var writtenModel = deserializer.Deserialize<YamlCommand>(output); - - Assert.Single(writtenModel.Syntaxes); - - var syntax = writtenModel.Syntaxes.Single(); - - Assert.Equal(model.Syntax.Single().ParameterSetName, syntax.ParameterValueGroup); - - Assert.Single(syntax.Parameters); - Assert.Equal(model.Syntax.Single().Parameters.Single().Name, syntax.Parameters.Single()); - } - - private static MamlCommand CreateModel() - { - var command = new MamlCommand - { - Name = "Test-Unit", - Description = new SectionBody("A test cmdlet"), - Synopsis = new SectionBody("A cmdlet to test"), - Notes = new SectionBody("This is just a test"), - ModuleName = "TestModule" - }; - - command.Examples.Add(new MamlExample - { - Remarks = "Example 1 remarks", - Code = new [] { new MamlCodeBlock("Example 1 code") }, - Introduction = "Example 1 intro", - Title = "Example 1 title" - }); - - command.Inputs.Add(new MamlInputOutput - { - Description = "Input 1", - TypeName = "System.String" - }); - - command.Links.Add(new MamlLink - { - LinkUri = "https://docs.microsoft.com", - LinkName = "Docs" - }); - - var mamlOptionalParameter = new MamlParameter - { - Required = false, - Name = "-TestParam", - Globbing = true, - Aliases = new [] {"-Alias1"}, - DefaultValue = "Test", - Description = "Test Parameter", - PipelineInput = "false", - Position = "1", - Type = "System.String" - }; - mamlOptionalParameter.ParameterValueGroup.Add("TestGroup"); - - var mamlRequiredParameter = new MamlParameter - { - Required = true, - Name = "-TestParam2", - Globbing = false, - Aliases = new[] { "-Alias2" }, - DefaultValue = "Test2", - Description = "Test Parameter 2", - PipelineInput = "true", - Position = "2", - Type = "System.Boolean" - }; - mamlRequiredParameter.ParameterValueGroup.Add("TestGroup2"); - - command.Parameters.AddRange(new [] {mamlRequiredParameter, mamlOptionalParameter}); - - command.Outputs.Add(new MamlInputOutput - { - Description = "Output 1", - TypeName = "System.String" - }); - - var mamlSyntax = new MamlSyntax - { - ParameterSetName = "TestGroup", - IsDefault = true - }; - mamlSyntax.Parameters.Add(mamlOptionalParameter); - command.Syntax.Add(mamlSyntax); - - return command; - } - - private static Deserializer CreateDeserializer() - { - return new DeserializerBuilder() - .WithNamingConvention(new CamelCaseNamingConvention()) - .Build(); - } - } -} diff --git a/v1/test/Markdown.MAML.Test/Transformer/MamlModelMergerTests.cs b/v1/test/Markdown.MAML.Test/Transformer/MamlModelMergerTests.cs deleted file mode 100644 index 3a9fef94..00000000 --- a/v1/test/Markdown.MAML.Test/Transformer/MamlModelMergerTests.cs +++ /dev/null @@ -1,228 +0,0 @@ -using Markdown.MAML.Model.MAML; -using Markdown.MAML.Model.Markdown; -using Markdown.MAML.Transformer; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Xunit; - -namespace Markdown.MAML.Test.Transformer -{ - public class MamlModelMergerTests - { - private string _reportStream; - - [Fact] - public void RendererProduceMarkdownV2Output() - { - var merger = new MamlModelMerger(WriteMessage); - var originalCommand = GetOriginal(); - var metadataCommand = GetRegenerated(); - - var result = merger.Merge(metadataCommand, originalCommand, updateInputOutput: false); - - Assert.Equal(3, result.Parameters.Count); - Assert.Equal(3, originalCommand.Parameters.Count); - Assert.Equal("Name", result.Parameters[0].Name); - Assert.Equal("NewParam", result.Parameters[1].Name); - Assert.Contains("Parameter Updated: Name", _reportStream); - Assert.Contains("Parameter Set Added: AnotherName", _reportStream); - Assert.Contains("Parameter Set Deleted: ByName", _reportStream); - Assert.Contains("Old Set: SetOldName", _reportStream); - Assert.Contains("New Set: SetNewName", _reportStream); - Assert.Contains("Parameter Added: NewParam", _reportStream); - Assert.Contains("Parameter Deleted: Remove", _reportStream); - Assert.Contains("---- UPDATING Cmdlet : Get-Foo ----", _reportStream); - Assert.Contains("---- COMPLETED UPDATING Cmdlet : Get-Foo ----\r\n\r\n", _reportStream); - - Assert.Equal(originalCommand.Synopsis.Text, result.Synopsis.Text); - Assert.Equal(originalCommand.Description.Text, result.Description.Text); - Assert.Equal(originalCommand.Notes.Text, result.Notes.Text); - Assert.Equal(originalCommand.Parameters[0].Description, result.Parameters[0].Description); - Assert.Equal(originalCommand.Parameters[0].FormatOption, result.Parameters[0].FormatOption); - Assert.Equal(originalCommand.Parameters[2].Description, result.Parameters[2].Description); - Assert.Equal(originalCommand.Parameters[2].FormatOption, result.Parameters[2].FormatOption); - - Assert.Equal(originalCommand.Links.Count, result.Links.Count); - Assert.Equal(originalCommand.Links[0].LinkName, result.Links[0].LinkName); - Assert.Equal(originalCommand.Links[0].LinkUri, result.Links[0].LinkUri); - } - - private void WriteMessage(string message) - { - _reportStream += message; - } - - private MamlCommand GetOriginal() - { - MamlCommand originalCommand = new MamlCommand() - { - Name = "Get-Foo", - Synopsis = new SectionBody("This is the synopsis"), - Description = new SectionBody("This is a long description.\r\nWith two paragraphs."), - Notes = new SectionBody("This is a multiline note.\r\nSecond line.") - }; - - var parameterName = new MamlParameter() - { - Type = "String", - Name = "Name", - Required = true, - Description = "Parameter Description.", - VariableLength = true, - Globbing = true, - PipelineInput = "True (ByValue)", - Position = "1", - DefaultValue = "trololo", - Aliases = new string[] { "GF", "Foos", "Do" }, - }; - var removedParameterName = new MamlParameter() - { - Type = "int", - Name = "Remove", - Required = true, - Description = "Parameter Description 2.", - VariableLength = true, - Globbing = true, - PipelineInput = "True (ByValue)", - Position = "2", - DefaultValue = "dodododo", - Aliases = new string[] { "Pa1", "RemovedParam", "Gone" }, - }; - var parameterPath = new MamlParameter() - { - Type = "String", - Name = "Path", - Required = true, - Description = "Parameter path description.", - FormatOption = SectionFormatOption.LineBreakAfterHeader, - Globbing = true - }; - - originalCommand.Parameters.Add(parameterName); - originalCommand.Parameters.Add(removedParameterName); - originalCommand.Parameters.Add(parameterPath); - - var syntax1 = new MamlSyntax() - { - ParameterSetName = "ByName", - }; - syntax1.Parameters.Add(parameterName); - syntax1.Parameters.Add(removedParameterName); - syntax1.Parameters.Add(parameterPath); - originalCommand.Syntax.Add(syntax1); - - var syntax2 = new MamlSyntax() - { - ParameterSetName = "SetOldName", - IsDefault = true - }; - syntax2.Parameters.Add(parameterName); - syntax2.Parameters.Add(parameterPath); - originalCommand.Syntax.Add(syntax2); - - originalCommand.Inputs.Add(new MamlInputOutput() - { - TypeName = "String", - Description = "Input <Description> goes here!" - - } - ); - originalCommand.Outputs.Add(new MamlInputOutput() - { - TypeName = "String", - Description = "Output Description goes here!" - } - ); - originalCommand.Examples.Add(new MamlExample() - { - Title = "Example 1", - Code = new[] { new MamlCodeBlock("PS:> Get-Help -YouNeedIt") }, - Remarks = "This does stuff!" - } - ); - originalCommand.Links.Add(new MamlLink() - { - LinkName = "PowerShell made by Microsoft Hackathon", - LinkUri = "www.microsoft.com" - - }); - - originalCommand.Links.Add(new MamlLink() - { - LinkName = "", // if name is empty, it would be populated with uri - LinkUri = "http://foo.com" - }); - - return originalCommand; - } - - private MamlCommand GetRegenerated() - { - MamlCommand metadataCommand = new MamlCommand() - { - Name = "Get-Foo", - Description = new SectionBody("This is a long description.\r\nWith two paragraphs."), - Synopsis = new SectionBody("This is a old synopsis."), // DIFF!! - Notes = new SectionBody("These are old notes") // DIFF!! - }; - - var parameterName1 = new MamlParameter() - { - Type = "String[]", // DIFF!! - Name = "Name", - Description = "Old Description", - Required = true, - VariableLength = true, - Globbing = false, // DIFF!! - PipelineInput = "True (ByValue)", - Position = "Named", // DIFF!! - Aliases = new string[]{"GF","Foo","Bar"} - }; - - var parameterNew = new MamlParameter() - { - Type = "String", - Name = "NewParam", - Description = "Old Param Description" - }; - - var parameterPath = new MamlParameter() - { - Type = "String", - Name = "Path", - Required = true, - Description = "Parameter path description.", - Globbing = true - }; - - metadataCommand.Parameters.Add(parameterName1); - metadataCommand.Parameters.Add(parameterNew); - metadataCommand.Parameters.Add(parameterPath); - - var syntax3 = new MamlSyntax() - { - ParameterSetName = "AnotherName" - }; - - syntax3.Parameters.Add(parameterName1); - syntax3.Parameters.Add(parameterNew); - syntax3.Parameters.Add(parameterPath); - metadataCommand.Syntax.Add(syntax3); - - var syntax4 = new MamlSyntax() - { - ParameterSetName = "SetNewName", - IsDefault = true - }; - - syntax4.Parameters.Add(parameterName1); - syntax4.Parameters.Add(parameterPath); - metadataCommand.Syntax.Add(syntax4); - - return metadataCommand; - } - } -} diff --git a/v1/test/Markdown.MAML.Test/Transformer/MamlMultiModelMergerTests.cs b/v1/test/Markdown.MAML.Test/Transformer/MamlMultiModelMergerTests.cs deleted file mode 100644 index ff703c9e..00000000 --- a/v1/test/Markdown.MAML.Test/Transformer/MamlMultiModelMergerTests.cs +++ /dev/null @@ -1,541 +0,0 @@ -using Markdown.MAML.Model.MAML; -using Markdown.MAML.Transformer; -using Markdown.MAML.Renderer; -using System.Collections.Generic; -using System.Linq; -using Xunit; -using Markdown.MAML.Model.Markdown; - -namespace Markdown.MAML.Test.Transformer -{ - public class MamlMultiModelMergerTests - { - [Fact] - public void Merge3SimpleModels() - { - var merger = new MamlMultiModelMerger(null, false, "! "); - var input = new Dictionary<string, MamlCommand>(); - input["First"] = GetModel1(); - input["Second"] = GetModel2(); - input["Third"] = GetModel3(); - - var result = merger.Merge(input); - - Common.AssertMultilineEqual(result.Synopsis.Text, @"! First, Second - -This is the synopsis - -! Third - -This is the synopsis 3 - -"); - - Assert.Equal("This is a long description.\r\nWith two paragraphs.", result.Description.Text); - - Common.AssertMultilineEqual(result.Notes.Text, @"! First - -This is a multiline note. -Second line. -First Command - -! Second - -This is a multiline note. -Second line. -Second Command - -! Third - -This is a multiline note. -Second line. -Third Command - -"); - - // Links - Assert.Equal(2, result.Links.Count); - Assert.Equal("[foo]()\r\n\r\n", result.Links.ElementAt(0).LinkName); - Assert.Equal("[bar]()\r\n\r\n", result.Links.ElementAt(1).LinkName); - - // Examples - Assert.Equal(2, result.Examples.Count); - Assert.Equal("Example 1 (Second)", result.Examples.ElementAt(0).Title); - Assert.Equal("Example 1 (Third)", result.Examples.ElementAt(1).Title); - - // Inputs - Assert.Equal(2, result.Inputs.Count); - Assert.Equal("String", result.Inputs.ElementAt(0).TypeName); - Assert.Equal("Foo", result.Inputs.ElementAt(0).Description); - Assert.Equal("String", result.Inputs.ElementAt(1).TypeName); - Assert.Equal("Foo 2", result.Inputs.ElementAt(1).Description); - - // Output - Assert.Single(result.Outputs); - Assert.Equal("String", result.Outputs.ElementAt(0).TypeName); - Assert.Null(result.Outputs.ElementAt(0).Description); - - // Syntax - Assert.Equal(2, result.Syntax.Count); - Assert.Equal("ByName", result.Syntax.ElementAt(0).ParameterSetName); - Assert.Equal(2, result.Syntax.ElementAt(0).Parameters.Count); - Assert.Equal("Name", result.Syntax.ElementAt(0).Parameters[0].Name); - Assert.Equal("Remove", result.Syntax.ElementAt(0).Parameters[1].Name); - - Assert.Equal("BySomethingElse", result.Syntax.ElementAt(1).ParameterSetName); - - // Parameters - Assert.Equal(2, result.Parameters.Count); - - Assert.Equal("Name", result.Parameters[0].Name); - Assert.Equal(new string[] { "First", "Second", "Third" }, result.Parameters[0].Applicable); - - Assert.Equal("Remove", result.Parameters[1].Name); - Assert.Equal(new string[] { "Third" }, result.Parameters[1].Applicable); - } - - private MamlCommand GetModel1() - { - MamlCommand command = new MamlCommand() - { - Name = "Get-Foo", - Synopsis = new SectionBody("This is the synopsis"), - Description = new SectionBody("This is a long description.\r\nWith two paragraphs."), - Notes = new SectionBody("This is a multiline note.\r\nSecond line.\r\nFirst Command") - }; - - command.Links.Add(new MamlLink(true) - { - LinkName = "[foo]()\r\n", - }); - - command.Inputs.Add(new MamlInputOutput() - { - TypeName = "String", - Description = "Foo" - - } - ); - - command.Outputs.Add(new MamlInputOutput() - { - TypeName = "String", - Description = null - } - ); - - var parameterName = new MamlParameter() - { - Type = "String", - Name = "Name", - Required = true, - Description = "Parameter Description.", - VariableLength = true, - Globbing = true, - PipelineInput = "True (ByValue)", - Position = "1", - DefaultValue = "trololo", - Aliases = new string[] { "GF", "Foos", "Do" }, - }; - - command.Parameters.Add(parameterName); - - var syntax1 = new MamlSyntax() - { - ParameterSetName = "ByName", - }; - syntax1.Parameters.Add(parameterName); - command.Syntax.Add(syntax1); - - return command; - } - - private MamlCommand GetModel2() - { - MamlCommand command = new MamlCommand() - { - Name = "Get-Foo", - Synopsis = new SectionBody("This is the synopsis"), - Description = new SectionBody("This is a long description.\r\nWith two paragraphs."), - Notes = new SectionBody("This is a multiline note.\r\nSecond line.\r\nSecond Command") - }; - - command.Links.Add(new MamlLink(true) - { - LinkName = "[foo]()\r\n[bar]()", - }); - - command.Examples.Add(new MamlExample() - { - Title = "Example 1", - Code = new[] { new MamlCodeBlock("PS:> Get-Help -YouNeedIt") }, - Remarks = "This does stuff!" - } - ); - - command.Inputs.Add(new MamlInputOutput() - { - TypeName = "String", - Description = "Foo" - - } - ); - - var parameterName = new MamlParameter() - { - Type = "String", - Name = "Name", - Required = true, - Description = "Parameter Description.", - VariableLength = true, - Globbing = true, - PipelineInput = "True (ByValue)", - Position = "1", - DefaultValue = "trololo", - Aliases = new string[] { "GF", "Foos", "Do" }, - }; - - command.Parameters.Add(parameterName); - - var syntax1 = new MamlSyntax() - { - ParameterSetName = "ByName", - }; - syntax1.Parameters.Add(parameterName); - command.Syntax.Add(syntax1); - - return command; - } - - private MamlCommand GetModel3() - { - MamlCommand command = new MamlCommand() - { - Name = "Get-Foo", - Synopsis = new SectionBody("This is the synopsis 3"), - Description = new SectionBody("This is a long description.\r\nWith two paragraphs."), - Notes = new SectionBody("This is a multiline note.\r\nSecond line.\r\nThird Command") - }; - - command.Links.Add(new MamlLink(true) - { - LinkName = "[bar]()", - }); - - command.Examples.Add(new MamlExample() - { - Title = "Example 1", - Code = new[] { new MamlCodeBlock("PS:> Get-Help -YouNeedIt") }, - Remarks = "This does stuff too!" - } - ); - - command.Inputs.Add(new MamlInputOutput() - { - TypeName = "String", - Description = "Foo 2" - - } - ); - - command.Outputs.Add(new MamlInputOutput() - { - TypeName = "String", - Description = null - } - ); - - var parameterName = new MamlParameter() - { - Type = "String", - Name = "Name", - Required = true, - Description = "Parameter Description.", - VariableLength = true, - Globbing = true, - PipelineInput = "True (ByValue)", - Position = "1", - DefaultValue = "trololo", - Aliases = new string[] { "GF", "Foos", "Do" }, - }; - - var parameterRemoved = new MamlParameter() - { - Type = "int", - Name = "Remove", - Required = true, - Description = "Parameter Description 2.", - VariableLength = true, - Globbing = true, - PipelineInput = "True (ByValue)", - Position = "2", - DefaultValue = "dodododo", - Aliases = new string[] { "Pa1", "RemovedParam", "Gone" }, - }; - - command.Parameters.Add(parameterName); - command.Parameters.Add(parameterRemoved); - - var syntax1 = new MamlSyntax() - { - ParameterSetName = "ByName", - }; - syntax1.Parameters.Add(parameterName); - syntax1.Parameters.Add(parameterRemoved); - command.Syntax.Add(syntax1); - - var syntax2 = new MamlSyntax() - { - ParameterSetName = "BySomethingElse", - IsDefault = true - }; - syntax2.Parameters.Add(parameterName); - command.Syntax.Add(syntax2); - - return command; - } - } - - public class MamlMultiModelMergerSyntaxTests - { - [Fact] - public void MergeDefaultSyntaxAndCreateMarkdown() - { - // First merge two models with default syntax names - - var merger = new MamlMultiModelMerger(null, false, "! "); - var input = new Dictionary<string, MamlCommand>(); - input["First"] = GetModel1(); - input["Second"] = GetModel2(); - - var result = merger.Merge(input); - - // Syntax - Assert.Single(result.Syntax); - Assert.Null(result.Syntax.ElementAt(0).ParameterSetName); - Assert.True(result.Syntax.ElementAt(0).IsDefault); - - // Parameters - Assert.Equal(2, result.Parameters.Count); - - Assert.Equal("Name1", result.Parameters[0].Name); - Assert.Equal(new string[] { "First" }, result.Parameters[0].Applicable); - - Assert.Equal("Name2", result.Parameters[1].Name); - Assert.Equal(new string[] { "Second" }, result.Parameters[1].Applicable); - - // next render it as markdown and make sure that we don't crash - - var renderer = new MarkdownV2Renderer(MAML.Parser.ParserMode.FormattingPreserve); - string markdown = renderer.MamlModelToString(result, true); - - int yamlLinesCount = markdown.Split('\n').Select(s => s.Trim()).Where(s => s.Equals("```yaml")).Count(); - // verify that ```yaml are all on a separate line - Assert.Equal(2, yamlLinesCount); - } - - private MamlCommand GetModel1() - { - MamlCommand command = new MamlCommand() - { - Name = "Get-Foo", - Synopsis = new SectionBody("This is the synopsis"), - Description = new SectionBody("This is a long description.\r\nWith two paragraphs."), - Notes = new SectionBody("This is a multiline note.\r\nSecond line.\r\nFirst Command") - }; - - var parameterName = new MamlParameter() - { - Type = "String", - Name = "Name1", - Required = true, - Description = "Parameter Description.\r\n", - VariableLength = true, - Globbing = true, - PipelineInput = "True (ByValue)", - Position = "1", - DefaultValue = "trololo", - Aliases = new string[] { "GF", "Foos", "Do" }, - }; - - command.Parameters.Add(parameterName); - - var syntax1 = new MamlSyntax() { IsDefault = true }; - syntax1.Parameters.Add(parameterName); - command.Syntax.Add(syntax1); - - return command; - } - - private MamlCommand GetModel2() - { - MamlCommand command = new MamlCommand() - { - Name = "Get-Foo", - Synopsis = new SectionBody("This is the synopsis"), - Description = new SectionBody("This is a long description.\r\nWith two paragraphs."), - Notes = new SectionBody("This is a multiline note.\r\nSecond line.\r\nSecond Command") - }; - - var parameterName = new MamlParameter() - { - Type = "String", - Name = "Name2", - Required = true, - Description = "Parameter Description.\r\n", - VariableLength = true, - Globbing = true, - PipelineInput = "True (ByValue)", - Position = "1", - DefaultValue = "trololo", - Aliases = new string[] { "GF", "Foos", "Do" }, - }; - - command.Parameters.Add(parameterName); - - var syntax1 = new MamlSyntax() { IsDefault = true }; - syntax1.Parameters.Add(parameterName); - command.Syntax.Add(syntax1); - - return command; - } - } - - public class MamlMultiModelMergerExampleTest - { - [Fact] - public void Merge2ExamplesInOne() - { - // First merge two models with default syntax names - - var merger = new MamlMultiModelMerger(null, false, "! "); - var input = new Dictionary<string, MamlCommand>(); - - input["First"] = GetModel( - title: "Example 1", - code: "PS:> 1+1", - remarks: "Hello" - ); - input["Second"] = GetModel( - title: "Example 1", - code: "PS:> 1+1", - remarks: "Hello" - ); - - var result = merger.Merge(input); - - // Examples - Assert.Single(result.Examples); - Assert.Equal("Example 1", result.Examples.ElementAt(0).Title); - - // next render it as markdown and make sure that we don't crash - var renderer = new MarkdownV2Renderer(MAML.Parser.ParserMode.FormattingPreserve); - string markdown = renderer.MamlModelToString(result, true); - } - - [Fact] - public void MergeExamplesOrder() - { - // First merge two models with default syntax names - - var merger = new MamlMultiModelMerger(null, false, "! "); - var input = new Dictionary<string, MamlCommand>(); - - input["First"] = GetModel( - new [] - { - new MamlExample() { Title = "E1" }, - new MamlExample() { Title = "E2" }, - } - ); - input["Second"] = GetModel( - new [] - { - new MamlExample() { Title = "E2" }, - new MamlExample() { Title = "E1" }, - new MamlExample() { Title = "E3" }, - } - ); - - var result = merger.Merge(input); - - // Examples - Assert.Equal(3, result.Examples.Count); - Assert.Equal("E1", result.Examples.ElementAt(0).Title); - Assert.Equal("E2", result.Examples.ElementAt(1).Title); - Assert.Equal("E3 (Second)", result.Examples.ElementAt(2).Title); - - // next render it as markdown and make sure that we don't crash - var renderer = new MarkdownV2Renderer(MAML.Parser.ParserMode.FormattingPreserve); - string markdown = renderer.MamlModelToString(result, true); - } - - [Fact] - public void Merge3ExamplesIn2() - { - // First merge two models with default syntax names - - var merger = new MamlMultiModelMerger(null, false, "! "); - var input = new Dictionary<string, MamlCommand>(); - - input["First"] = GetModel( - title: "Example 1", - code: "PS:> 1+1", - remarks: "Hello" - ); - input["Second"] = GetModel( - title: "Example 1", - code: "PS:> 1+1", - remarks: "Hello" - ); - - input["Third"] = GetModel( - title: "Example 1", - code: "PS:> 1+1", - remarks: "Hello world" - ); - - var result = merger.Merge(input); - - // Examples - Assert.Equal(2, result.Examples.Count); - Assert.Equal("Example 1 (First, Second)", result.Examples.ElementAt(0).Title); - Assert.Equal("Hello", result.Examples.ElementAt(0).Remarks); - Assert.Equal("Example 1 (Third)", result.Examples.ElementAt(1).Title); - Assert.Equal("Hello world", result.Examples.ElementAt(1).Remarks); - - // next render it as markdown and make sure that we don't crash - var renderer = new MarkdownV2Renderer(MAML.Parser.ParserMode.FormattingPreserve); - string markdown = renderer.MamlModelToString(result, true); - } - - private MamlCommand GetModel(string title, string code, string remarks) - { - MamlCommand command = new MamlCommand() - { - Name = "Get-Foo", - }; - - command.Examples.Add(new MamlExample() - { - Title = title, - Code = new[] { new MamlCodeBlock(code) }, - Remarks = remarks, - } - ); - - return command; - } - - private MamlCommand GetModel(MamlExample[] examples) - { - MamlCommand command = new MamlCommand() - { - Name = "Get-Foo", - }; - - command.Examples.AddRange(examples); - return command; - } - } -} diff --git a/v1/test/Markdown.MAML.Test/Transformer/ParserAndTransformerTestsV2.cs b/v1/test/Markdown.MAML.Test/Transformer/ParserAndTransformerTestsV2.cs deleted file mode 100644 index 37ebae58..00000000 --- a/v1/test/Markdown.MAML.Test/Transformer/ParserAndTransformerTestsV2.cs +++ /dev/null @@ -1,1139 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Markdown.MAML.Model.MAML; -using Markdown.MAML.Parser; -using Markdown.MAML.Transformer; -using Xunit; -using Markdown.MAML.Model.Markdown; - -namespace Markdown.MAML.Test.Transformer -{ - public class ParserAndTransformerTestsV2 - { - [Fact] - public void TransformSimpleCommand() - { - - var doc = ParseString(@" -# Get-Foo -## Synopsis -This is Synopsis -"); - MamlCommand mamlCommand = NodeModelToMamlModelV2(doc).First(); - Assert.Equal("Get-Foo", mamlCommand.Name); - Assert.Equal("This is Synopsis", mamlCommand.Synopsis.Text); - } - - [Fact] - public void TransformSynopsisWithHyperlink() - { - - var doc = ParseString(@" -# Get-Foo -## Synopsis -Here is a [hyperlink](http://non-existing-uri). -"); - MamlCommand mamlCommand = NodeModelToMamlModelV2(doc).First(); - Assert.Equal("Get-Foo", mamlCommand.Name); - Assert.Equal("Here is a hyperlink (http://non-existing-uri).", mamlCommand.Synopsis.Text); - } - - [Fact] - public void SkipYamlMetadataBlock() - { - - var doc = ParseString(@" ---- -foo: bar -baz: foo -schema: 2.0.0 ---- - -# Get-Foo -## Synopsis -This is Synopsis -"); - MamlCommand mamlCommand = NodeModelToMamlModelV2(doc).First(); - Assert.Equal("Get-Foo", mamlCommand.Name); - Assert.Equal("This is Synopsis", mamlCommand.Synopsis.Text); - } - - [Fact] - public void TransformCommandWithExtraLine() - { - var doc = ParseString(@" -#Add-Member - -##SYNOPSIS -Adds custom properties and methods to an instance of a Windows PowerShell object. - -"); - MamlCommand mamlCommand = NodeModelToMamlModelV2(doc).First(); - Assert.Equal("Add-Member", mamlCommand.Name); - Assert.Equal("Adds custom properties and methods to an instance of a Windows PowerShell object.", mamlCommand.Synopsis.Text); - } - - [Fact] - public void TransformCommandWithHeaderLineBreak() - { - var doc = ParseString(@" -#Add-Member - -##SYNOPSIS - -Adds custom properties and methods to an instance of a Windows PowerShell object."); - MamlCommand mamlCommand = NodeModelToMamlModelV2(doc).First(); - Assert.Equal("Add-Member", mamlCommand.Name); - Assert.Equal("Adds custom properties and methods to an instance of a Windows PowerShell object.", mamlCommand.Synopsis.Text); - Assert.Equal(SectionFormatOption.LineBreakAfterHeader, mamlCommand.Synopsis.FormatOption); - } - - [Fact] - public void TransformCommandWithParameterHeaderLineBreak() - { - var doc = ParseString(@" -# Add-Member - -## PARAMETERS - -### -Name - -This is the name parameter. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: True -Position: 0 -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` -"); - MamlCommand mamlCommand = NodeModelToMamlModelV2(doc).First(); - Assert.Equal("This is the name parameter.", mamlCommand.Parameters[0].Description); - Assert.Equal(SectionFormatOption.LineBreakAfterHeader, mamlCommand.Parameters[0].FormatOption); - } - - [Fact] - public void TransformCommandWithExampleHeaderLineBreak() - { - var doc = ParseString(@" -# Add-Member - -## EXAMPLES - -### Example 1 - -This is an example. - -```powershell -PS C:\> Get-PSDocumentHeader -Path '.\build\Default\Server1.md'; -``` - -``` -Output -``` - -### Example 2 -This is an example. - -``` -PS C:\> Get-PSDocumentHeader -Path '.\build\Default\Server1.md'; -``` - -``` -Get-PSDocumentHeader -Path '.\build\Default\Server1.md'; -``` - -``` -Output -``` -"); - MamlCommand mamlCommand = NodeModelToMamlModelV2(doc).First(); - - // Check the number of examples - Assert.Equal(2, mamlCommand.Examples.Count); - - // Confirm example fields and code block language is read - Assert.Equal("This is an example.", mamlCommand.Examples[0].Introduction); - Assert.Equal(SectionFormatOption.LineBreakAfterHeader, mamlCommand.Examples[0].FormatOption); - Assert.Equal(2, mamlCommand.Examples[0].Code.Length); - Assert.Equal("powershell", mamlCommand.Examples[0].Code[0].LanguageMoniker); - Assert.Equal(string.Empty, mamlCommand.Examples[0].Code[1].LanguageMoniker); - - // Confirm example fields - Assert.Equal(SectionFormatOption.None, mamlCommand.Examples[1].FormatOption); - } - - [Fact] - public void TransformMultilineDescription() - { - - var doc = ParseString(@" -# Get-Foo -## Synopsis -This is Synopsis, but it doesn't matter in this test - -## DESCRIPTION -Hello, - -I'm a multiline description. - -And this is my last line. -"); - MamlCommand mamlCommand = NodeModelToMamlModelV2(doc).First(); - string[] description = mamlCommand.Description.Text.Split('\n').Select(x => x.Trim()).ToArray(); - Assert.Equal(3, description.Length); - Assert.Equal("Hello,", description[0]); - Assert.Equal("I'm a multiline description.", description[1]); - Assert.Equal("And this is my last line.", description[2]); - Assert.False(mamlCommand.SupportCommonParameters); - } - - [Fact] - public void RecogniceTwoCommandsWithDifferentOrdersOfEntries() - { - - var doc = ParseString(@" -# Get-Foo -## Synopsis -This is Synopsis, but it doesn't matter in this test -## DESCRIPTION -This is description - -# Get-Bar -## DESCRIPTION -This is description -## Synopsis -This is Synopsis, but it doesn't matter in this test - -"); - var mamlCommand = NodeModelToMamlModelV2(doc).ToArray(); - Assert.Equal(2, mamlCommand.Count()); - Assert.NotNull(mamlCommand[0].Description); - Assert.NotNull(mamlCommand[0].Synopsis); - Assert.NotNull(mamlCommand[1].Description); - Assert.NotNull(mamlCommand[1].Synopsis); - } - - [Fact] - public void SingleParameter() - { - - var doc = ParseString(@" -# Get-Foo -## Parameters -### Bar -This is bar parameter - -```yaml -Required: true -Position: named -Default value: Fooo -Accept pipeline input: false -Accept wildcard characters: true -``` - -"); - var mamlCommand = NodeModelToMamlModelV2(doc).ToArray(); - Assert.Single(mamlCommand); - var param = mamlCommand[0].Parameters.ToArray(); - Assert.Single(param); - Assert.Equal("Bar", param[0].Name); - Assert.Equal("This is bar parameter", param[0].Description); - Assert.Equal("Fooo", param[0].DefaultValue); - Assert.Equal("false", param[0].PipelineInput); - Assert.True(param[0].Globbing); - } - - [Fact] - public void SingleYamlApplicableParameter() - { - - var doc = ParseString(@" -# Get-Foo -## Parameters -### Bar1 -This is bar parameter - -```yaml -Required: true -Position: named -Default value: Fooo -Accept pipeline input: false -Accept wildcard characters: true -Applicable: fOo, bAr -``` -### Bar2 -This is bar parameter - -```yaml -Required: true -Position: named -Default value: Fooo -Accept pipeline input: false -Accept wildcard characters: true -Applicable: baz -``` - -### Bar3 -This is bar parameter - -```yaml -Required: true -Position: named -Default value: Fooo -Accept pipeline input: false -Accept wildcard characters: true -``` - -### Bar4 -This is bar parameter - -```yaml -Required: true -Position: named -Default value: Fooo -Accept pipeline input: false -Accept wildcard characters: true -Applicable: tag -``` - -"); - var mamlCommand = NodeModelToMamlModelV2(doc, new[] { "foo", "tag" }).ToArray(); - Assert.Single(mamlCommand); - var param = mamlCommand[0].Parameters.ToArray(); - Assert.Equal(3, param.Count()); - // Bar1 has Applicable "foo" - Assert.Equal("Bar1", param[0].Name); - // Bar2 should not match - // Bar3 has no applicable - Assert.Equal("Bar3", param[1].Name); - // Bar4 has Applicable "tag" - Assert.Equal("Bar4", param[2].Name); - } - - // For more context see https://github.com/PowerShell/platyPS/issues/239 - [Fact] - public void SingleParameterWithCodesnippet() - { - - var doc = ParseString(@" -# Get-Foo -## Parameters -### Bar -This is bar parameter - -``` -// With a codesnippet -``` - -And something else - -```yaml -Required: true -Position: named -Default value: Fooo -Accept pipeline input: false -Accept wildcard characters: true -``` - -"); - var mamlCommand = NodeModelToMamlModelV2(doc).ToArray(); - Assert.Single(mamlCommand); - var param = mamlCommand[0].Parameters.ToArray(); - Assert.Single(param); - Assert.Equal("Bar", param[0].Name); - Assert.Equal("This is bar parameter\r\n\r\n// With a codesnippet\r\n\r\nAnd something else", param[0].Description); - } - - [Fact] - public void InputAndOutput() - { - - var doc = ParseString(@" -# Get-Foo -## INPUTS -### System.String -You can pipe computer names and new names to the Add-ComputerCmdlet. - -## OUTPUTS -### Microsoft.PowerShell.Commands.ComputerChangeInfo - -"); - var mamlCommand = NodeModelToMamlModelV2(doc).ToArray(); - Assert.Single(mamlCommand); - var inputs = mamlCommand[0].Inputs.ToArray(); - var outputs = mamlCommand[0].Outputs.ToArray(); - Assert.Single(inputs); - Assert.Single(outputs); - Assert.Equal("System.String", inputs[0].TypeName); - Assert.Equal("Microsoft.PowerShell.Commands.ComputerChangeInfo", outputs[0].TypeName); - Assert.Equal("You can pipe computer names and new names to the Add-ComputerCmdlet.", inputs[0].Description); - Assert.Empty(outputs[0].Description); - } - - [Fact] - public void Produce2Examples() - { - - var doc = ParseString(@" -# Get-Foo - -## NOTES - -## EXAMPLES -### --EXAMPLE1-- -Introduction -``` -# PS code here -``` -Remarks - -### --EXAMPLE2-- -Introduction -``` -# PS code here -``` -```powershell -# PS More code here -``` -Remarks - -"); - var mamlCommand = NodeModelToMamlModelV2(doc).ToArray(); - Assert.Single(mamlCommand); - var examples = mamlCommand[0].Examples.ToArray(); - Assert.Equal(2, examples.Count()); - Assert.Equal("--EXAMPLE1--", examples[0].Title); - Assert.Equal("# PS code here", examples[0].Code[0].Text); - Assert.Equal("Remarks", examples[0].Remarks); - Assert.Equal("Introduction", examples[0].Introduction); - Assert.Equal("# PS code here", examples[1].Code[0].Text); - Assert.Equal("# PS More code here", examples[1].Code[1].Text); - Assert.Equal("powershell", examples[1].Code[1].LanguageMoniker); - } - - [Fact] - public void ProduceRelatedLinks() - { - - var doc = ParseString(@" -# Get-Foo -##RELATED LINKS - -[Online Version:](http://go.microsoft.com/fwlink/p/?linkid=289795) - -[Checkpoint-Computer]() - -[Remove-Computer]() - -[Restart-Computer]() - -[Rename-Computer]() - -[Restore-Computer]() - -[Stop-Computer]() - -[Test-Connection]() -"); - var mamlCommand = NodeModelToMamlModelV2(doc).ToArray(); - Assert.Single(mamlCommand); - var links = mamlCommand[0].Links.ToArray(); - Assert.Equal(8, links.Count()); - Assert.Equal("Online Version:", links[0].LinkName); - Assert.Equal("http://go.microsoft.com/fwlink/p/?linkid=289795", links[0].LinkUri); - Assert.Equal("Checkpoint-Computer", links[1].LinkName); - Assert.Empty(links[1].LinkUri); - } - - [Fact] - public void HandlesHyperLinksInsideText() - { - var doc = ParseString(@" -# Get-Foo -## SYNOPSIS -Runs the [Set-WSManQuickConfig]() cmdlet - -"); - var mamlCommand = NodeModelToMamlModelV2(doc).ToArray(); - Assert.Single(mamlCommand); - Assert.Equal("Runs the Set-WSManQuickConfig cmdlet", mamlCommand[0].Synopsis.Text); - } - - [Fact] - public void HandlesItalicInsideText() - { - var doc = ParseString(@" -# Get-Foo -## SYNOPSIS -Runs the *Set-WSManQuickConfig* cmdlet - -"); - var mamlCommand = NodeModelToMamlModelV2(doc).ToArray(); - Assert.Single(mamlCommand); - Assert.Equal("Runs the Set-WSManQuickConfig cmdlet", mamlCommand[0].Synopsis.Text); - } - - [Fact] - public void HandlesBoldInsideText() - { - var doc = ParseString(@" -# Get-Foo -## SYNOPSIS -Runs the **Set-WSManQuickConfig** cmdlet - -"); - var mamlCommand = NodeModelToMamlModelV2(doc).ToArray(); - Assert.Single(mamlCommand); - Assert.Equal("Runs the Set-WSManQuickConfig cmdlet", mamlCommand[0].Synopsis.Text); - } - - [Fact] - public void ProducesParameterAndSyntaxEntries() - { - - - const string fooParamName = "FooParam"; - const string fooAttributes = @" -Type: string - -Required: true -Position: 0 -Default value: None -Accept pipeline input: true (ByValue, ByPropertyName) -Accept wildcard characters: false -"; - - const string barParamName = "BarParam"; - const string barAttributes = @" -Type: double -Parameter Sets: BarParamSet -Aliases: br - -Required: true -Position: 0 -Default value: None -Accept pipeline input: true (ByValue, ByPropertyName) -Accept wildcard characters: false -"; - - const string bazParamName = "BazParam"; - const string bazAttributes = @" -Type: int -Parameter Sets: BazParamSet -Aliases: bz, z - -Required: false -Position: named -Default value: None -Accept pipeline input: false -Accept wildcard characters: false -"; - - const string docFormatString = @" -# Get-Foo -## PARAMETERS - -{0} -{1} -{2} -"; - var doc = - ParseString( - string.Format( - docFormatString, - GetParameterText(fooParamName, fooAttributes), - GetParameterText(barParamName, barAttributes), - GetParameterText(bazParamName, bazAttributes))); - - MamlCommand mamlCommand = NodeModelToMamlModelV2(doc).First(); - Assert.Equal("Get-Foo", mamlCommand.Name); - - Assert.Equal(3, mamlCommand.Parameters.Count); - - var fooParam = mamlCommand.Parameters[0]; - Assert.Equal(fooParamName, fooParam.Name); - Assert.Equal("string", fooParam.Type); - Assert.True(fooParam.Required); - Assert.Empty(fooParam.Aliases); - - var barParam = mamlCommand.Parameters[1]; - Assert.Equal(barParamName, barParam.Name); - Assert.Equal("double", barParam.Type); - Assert.True(barParam.Required); - Assert.Single(barParam.Aliases); - Assert.Contains("br", barParam.Aliases); - - var bazParam = mamlCommand.Parameters[2]; - Assert.Equal(bazParamName, bazParam.Name); - Assert.Equal("int", bazParam.Type); - Assert.False(bazParam.Required); - Assert.Equal(2, bazParam.Aliases.Length); - Assert.Contains("bz", bazParam.Aliases); - Assert.Contains("z", bazParam.Aliases); - - Assert.Equal(2, mamlCommand.Syntax.Count); - Assert.Equal("FooParam", mamlCommand.Syntax[1].Parameters[0].Name); - Assert.Equal("BazParam", mamlCommand.Syntax[1].Parameters[1].Name); - Assert.Equal("FooParam", mamlCommand.Syntax[0].Parameters[0].Name); - Assert.Equal("BarParam", mamlCommand.Syntax[0].Parameters[1].Name); - } - - [Fact] - public void ProducesParameterEntriesForCornerCases() - { - - - const string docFormatString = @" -# Get-Foo -## PARAMETERS - -### NonExistingTypeParam -This is NonExistingTypeParam description. - -```yaml -Type: NonExistingType -``` - -### NoDescriptionParam - -```yaml -Type: string -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters]\(http://go.microsoft.com/fwlink/?LinkID=113216\). - -### NoTypeParam - -NoTypeParam description. -"; - var doc = ParseString(docFormatString); - - MamlCommand mamlCommand = NodeModelToMamlModelV2(doc).First(); - Assert.Equal("Get-Foo", mamlCommand.Name); - - Assert.Equal(3, mamlCommand.Parameters.Count); - - var nonExistinTypeParam = mamlCommand.Parameters[0]; - Assert.Equal("NonExistingTypeParam", nonExistinTypeParam.Name); - Assert.Equal("NonExistingType", nonExistinTypeParam.Type); - Assert.Equal("This is NonExistingTypeParam description.", nonExistinTypeParam.Description); - - var noDescriptionParam = mamlCommand.Parameters[1]; - Assert.Equal("NoDescriptionParam", noDescriptionParam.Name); - Assert.Equal("string", noDescriptionParam.Type); - Assert.Equal("", noDescriptionParam.Description); - Assert.True(noDescriptionParam.ValueRequired); - - var noTypeParam = mamlCommand.Parameters[2]; - Assert.Equal("NoTypeParam", noTypeParam.Name); - Assert.Null(noTypeParam.Type); - Assert.Equal("NoTypeParam description.", noTypeParam.Description); - - Assert.True(mamlCommand.SupportCommonParameters); - } - - [Fact] - public void ProducesParameterForDefaultParameterName() - { - - - const string docFormatString = @" -# Get-Foo -## PARAMETERS - -### informationVariable - -### force - -```yaml -Type: SwitchParameter -Required: false -``` -"; - var doc = ParseString(docFormatString); - - MamlCommand mamlCommand = NodeModelToMamlModelV2(doc).First(); - Assert.Equal("Get-Foo", mamlCommand.Name); - - Assert.Equal(2, mamlCommand.Parameters.Count); - - var informationVariable = mamlCommand.Parameters[0]; - Assert.Equal("informationVariable", informationVariable.Name); - Assert.Null(informationVariable.Type); - Assert.True(informationVariable.ValueRequired); - - var force = mamlCommand.Parameters[1]; - Assert.Equal("force", force.Name); - Assert.Equal("SwitchParameter", force.Type); - Assert.False(force.ValueRequired); - } - - [Fact] - public void ProducesParameterValueGroup() - { - - - const string docFormatString = @" -# Get-Foo -## PARAMETERS - -### foo -```yaml -Type: string -Accepted values: a, b, c -``` -"; - var doc = ParseString(docFormatString); - - MamlCommand mamlCommand = NodeModelToMamlModelV2(doc).First(); - Assert.Equal("Get-Foo", mamlCommand.Name); - - Assert.Single(mamlCommand.Syntax); - Assert.Single(mamlCommand.Syntax[0].Parameters); - - var fooParam = mamlCommand.Syntax[0].Parameters[0]; - Assert.Equal("foo", fooParam.Name); - Assert.Equal("string", fooParam.Type); - Assert.Equal(3, fooParam.ParameterValueGroup.Count); - Assert.Equal("a", fooParam.ParameterValueGroup[0]); - Assert.Equal("b", fooParam.ParameterValueGroup[1]); - Assert.Equal("c", fooParam.ParameterValueGroup[2]); - } - - [Fact] - public void ProducesSyntaxForTwoSets() - { - - - const string docFormatString = @" -# Get-Foo -## PARAMETERS - -### TypeName - -```yaml -Type: string -Parameter sets: Set 1 -Required: true -``` - -```yaml -Type: string -Parameter sets: Set 2 -Required: false -``` -"; - var doc = ParseString(docFormatString); - - MamlCommand mamlCommand = NodeModelToMamlModelV2(doc).First(); - Assert.Equal("Get-Foo", mamlCommand.Name); - - // Check Syntax - Assert.Equal(2, mamlCommand.Syntax.Count); - var syntax1 = mamlCommand.Syntax[0]; - var syntax2 = mamlCommand.Syntax[1]; - - Assert.Single(syntax1.Parameters); - Assert.Single(syntax2.Parameters); - - Assert.Equal("TypeName", syntax1.Parameters[0].Name); - Assert.Equal("TypeName", syntax2.Parameters[0].Name); - - Assert.Equal("string", syntax1.Parameters[0].Type); - Assert.Equal("string", syntax2.Parameters[0].Type); - - Assert.True(syntax1.Parameters[0].Required); - Assert.False(syntax2.Parameters[0].Required); - - // Check Parameters - Assert.Single(mamlCommand.Parameters); - var parameter = mamlCommand.Parameters[0]; - Assert.Equal("TypeName", parameter.Name); - // Required == true because first takes precedence - Assert.True(parameter.Required); - } - - [Fact] - public void ApplicableAndSyntaxForTwoSetsInterraction() - { - // we are mixing together two yaml definitions and applicable tag - - const string docFormatString = @" -# Get-Foo -## PARAMETERS - -### TypeName - -```yaml -Type: string -Parameter sets: Set 1 -Required: true -applicable: foo -``` - -```yaml -Type: string -Parameter sets: Set 2 -Required: false -Applicable: bar -``` -"; - var doc = ParseString(docFormatString); - - MamlCommand mamlCommand = NodeModelToMamlModelV2(doc, new[] { "bar" }).First(); - Assert.Equal("Get-Foo", mamlCommand.Name); - - Assert.Single(mamlCommand.Syntax); - var syntax1 = mamlCommand.Syntax[0]; - - Assert.Single(syntax1.Parameters); - Assert.Equal("TypeName", syntax1.Parameters[0].Name); - Assert.Equal("string", syntax1.Parameters[0].Type); - Assert.False(syntax1.Parameters[0].Required); - } - - [Fact] - public void ProducesSyntaxInTheRightOrder() - { - - - const string docFormatString = @" -# Get-Foo -## PARAMETERS - -### SecondSetParam - -```yaml -Type: String -Parameter sets: Set 2 -``` - -### FirstSetParam - -```yaml -Type: String -Parameter sets: Set 1 -``` - -"; - var doc = ParseString(docFormatString); - - MamlCommand mamlCommand = NodeModelToMamlModelV2(doc).First(); - Assert.Equal("Get-Foo", mamlCommand.Name); - - Assert.Equal(2, mamlCommand.Syntax.Count); - var syntax1 = mamlCommand.Syntax[0]; - var syntax2 = mamlCommand.Syntax[1]; - - Assert.Single(syntax1.Parameters); - Assert.Single(syntax2.Parameters); - - Assert.Equal("FirstSetParam", syntax2.Parameters[0].Name); - Assert.Equal("SecondSetParam", syntax1.Parameters[0].Name); - } - - [Fact] - public void ProducesParametersInTheRightOrderInSyntax() - { - - - const string docFormatString = @" -# Get-Foo -## PARAMETERS - -### -Third - -```yaml -Type: String -Position: 3 -``` - -### -Named - -```yaml -Type: String -Position: Named -``` - -### -First - -```yaml -Type: String -Position: 1 -``` - -"; - var doc = ParseString(docFormatString); - - MamlCommand mamlCommand = NodeModelToMamlModelV2(doc).First(); - Assert.Equal("Get-Foo", mamlCommand.Name); - - Assert.Single(mamlCommand.Syntax); - var syntax = mamlCommand.Syntax[0]; - - Assert.Equal(3, syntax.Parameters.Count); - - Assert.Equal("First", syntax.Parameters[0].Name); - Assert.Equal("Third", syntax.Parameters[1].Name); - Assert.Equal("Named", syntax.Parameters[2].Name); - } - - [Fact] - public void ProduceDefaultValues() - { - - - const string docFormatString = @" -# Get-Foo -## PARAMETERS - -### Name - -```yaml -Type: String -Parameter Sets: Set1 -Aliases: - -Required: False -Position: Named -Default value: PowerShell -Accept pipeline input: False -Accept wildcard characters: False -``` - -"; - var doc = ParseString(docFormatString); - - MamlCommand mamlCommand = NodeModelToMamlModelV2(doc).First(); - Assert.Equal("Get-Foo", mamlCommand.Name); - - Assert.Single(mamlCommand.Parameters); - var parameter = mamlCommand.Parameters[0]; - - Assert.Equal("PowerShell", parameter.DefaultValue); - } - - [Fact] - public void UsesEntryToMarkGlobbing() - { - - - const string docFormatString = @" -# Get-Foo -## PARAMETERS - -### Name - -```yaml -Type: string -Accept wildcard characters: true -``` - -"; - var doc = ParseString(docFormatString); - - MamlCommand mamlCommand = NodeModelToMamlModelV2(doc).First(); - Assert.Equal("Get-Foo", mamlCommand.Name); - - Assert.Single(mamlCommand.Parameters); - var parameter = mamlCommand.Parameters[0]; - - Assert.True(parameter.Globbing); - Assert.Equal("string", parameter.Type); - } - - [Fact] - public void ParseClearHistorySyntaxInTheRightOrder() - { - const string docFormatString = @" - -# Clear-History - -## SYNOPSIS -Deletes entries from the command history. - -## DESCRIPTION -The Clear-History cmdlet deletes commands from the command history, that is, the list of commands entered during the current session. -Without parameters, Clear-History deletes all commands from the session history, but you can use the parameters of Clear-History to delete selected commands. - -## PARAMETERS - -### Id -Deletes commands with the specified history IDs. -To find the history ID of a command, use Get-History. - -```yaml -Type: Int32[] -Parameter Sets: IDParameter -Aliases: - -Required: False -Position: 1 -Default value: None -Accept pipeline input: False -Accept wildcard characters: True -``` - -### Count -Clears the specified number of history entries, beginning with the oldest entry in the history. -If you use the Count and Id parameters in the same command, the cmdlet clears the number of entries specified by the Count parameter, beginning with the entry specified by the Id parameter. For example, if Count is 10 and Id is 30, Clear-History clears items 21 through 30 inclusive. -If you use the Count and CommandLine parameters in the same command, Clear-History clears the number of entries specified by the Count parameter, beginning with the entry specified by the CommandLine parameter. - -```yaml -Type: Int32 -Parameter Sets: IDParameter, CommandLineParameter -Aliases: - -Required: False -Position: 2 -Default value: -Accept pipeline input: False -Accept wildcard characters: True -``` - -### Newest -Deletes the newest entries in the history. By default, Clear-History deletes the oldest entries in the history. - -```yaml -Type: SwitchParameter -Parameter Sets: IDParameter, CommandLineParameter -Aliases: - -Required: False -Position: named -Default value: False -Accept pipeline input: False -Accept wildcard characters: True -``` - -### WhatIf -Shows what would happen if the cmdlet runs. The cmdlet is not run.Shows what would happen if the cmdlet runs. The cmdlet is not run. - -```yaml -Type: SwitchParameter -Parameter Sets: IDParameter, CommandLineParameter -Aliases: wi - -Required: False -Position: named -Default value: false -Accept pipeline input: False -Accept wildcard characters: True -``` - -### Confirm -Prompts you for confirmation before running the cmdlet.Prompts you for confirmation before running the cmdlet. - -```yaml -Type: SwitchParameter -Parameter Sets: IDParameter, CommandLineParameter -Aliases: cf - -Required: False -Position: named -Default value: false -Accept pipeline input: False -Accept wildcard characters: True -``` - -### CommandLine -Deletes commands with the specified text strings. If you enter more than one string, Clear-History deletes commands with any of the strings. - -```yaml -Type: String[] -Parameter Sets: CommandLineParameter -Aliases: - -Required: False -Position: named -Default value: -Accept pipeline input: False -Accept wildcard characters: True -``` -"; - var doc = ParseString(docFormatString); - - MamlCommand mamlCommand = NodeModelToMamlModelV2(doc).First(); - Assert.Equal("Clear-History", mamlCommand.Name); - - Assert.Equal(2, mamlCommand.Syntax.Count); - var syntax1 = mamlCommand.Syntax[0]; - var syntax2 = mamlCommand.Syntax[1]; - - Assert.Equal(5, syntax1.Parameters.Count); - Assert.Equal(5, syntax2.Parameters.Count); - - Assert.Equal("Id", syntax1.Parameters[0].Name); - Assert.Equal("Count", syntax2.Parameters[0].Name); - } - - [Fact] - public void PreserveFormattingIfNeeded() - { - const string description = @"Hello - -This description block test formatting preservance. --- It need to --- Be. Very. [Weiredly](formatted) - - - -\< to keep > the purpose. \\( \\\( \( - This is intentional. -* we - -* dont't want. * Mess up with user's formatting. -"; - - const string docFormatString = @" -# Get-Foo -## DESCRIPTION -" + description; - var doc = ParseStringPreserveFormat(docFormatString); - - MamlCommand mamlCommand = NodeModelToMamlModelV2(doc).First(); - Assert.Equal("Get-Foo", mamlCommand.Name); - - Common.AssertMultilineEqual(description, mamlCommand.Description.Text); - } - - private DocumentNode ParseString(string markdown) - { - var parser = new MarkdownParser(); - return parser.ParseString(new string[] { markdown }); - } - - private DocumentNode ParseStringPreserveFormat(string markdown) - { - var parser = new MarkdownParser(); - return parser.ParseString(new string[] { markdown }, ParserMode.FormattingPreserve, null); - } - - private static string GetParameterText(string paramName, string paramAttributes) - { - const string paramFormatString = @" -### {0} - -This is the documentation for {0} - -```yaml -{1} -``` - -"; - return string.Format(paramFormatString, paramName, paramAttributes); - } - - private IEnumerable<MamlCommand> NodeModelToMamlModelV2(DocumentNode doc, string[] applicableTag = null) - { - return (new ModelTransformerVersion2(null, null, applicableTag)).NodeModelToMamlModel(doc); - } - } -} diff --git a/v1/test/Pester/FullLoop.Tests.ps1 b/v1/test/Pester/FullLoop.Tests.ps1 deleted file mode 100644 index fca70a1a..00000000 --- a/v1/test/Pester/FullLoop.Tests.ps1 +++ /dev/null @@ -1,255 +0,0 @@ -Set-StrictMode -Version latest -$ErrorActionPreference = 'Stop' - -$root = (Resolve-Path $PSScriptRoot\..\..).Path -$outFolder = "$root\out" - -Import-Module $outFolder\platyPS -Force -$MyIsLinux = Get-Variable -Name IsLinux -ValueOnly -ErrorAction SilentlyContinue -$MyIsMacOS = Get-Variable -Name IsMacOS -ValueOnly -ErrorAction SilentlyContinue -<# -Describe 'Full loop for Add-Member cmdlet' { - - $cmdlet = "Add-Member" - # run convertion - $file = New-MarkdownHelp -command $cmdlet -OutputFolder $outFolder -Force -Encoding ([System.Text.Encoding]::UTF8) - - It 'generate correct file name' { - $file.FullName | Should Be (Join-Path $outFolder "$cmdlet.md") - } - - It 'writes nothing if content is not changing' { - {New-MarkdownHelp -command $cmdlet -OutputFolder $outFolder -Encoding ([System.Text.Encoding]::UTF8) -ea Stop} | Should -Not -Throw - } - - # test -MarkdownFile piping - $generatedMaml = $file | New-ExternalHelp -Verbose -OutputPath $outFolder -Force - - It 'generate maml as a valid xml' { - [xml]($generatedMaml | Get-Content -raw) | Should Not Be $null - } - - $generatedHelpObject = Get-HelpPreview $generatedMaml - - $originalHelpObject = Get-Help -Name "Microsoft.PowerShell.Utility\$cmdlet" - - Context 'markdown metadata' { - $h = Get-MarkdownMetadata $file - It 'online version is available in metadata and metadata is case-insensitive' { - $h['oNline vErsion'] | Should Be $originalHelpObject.relatedLinks.navigationLink[0].uri - } - } - - It 'generate correct Name' { - $generatedHelpObject.Name | Should Be $originalHelpObject.Name - } - - It 'generate correct Synopsis' { - $generatedHelpObject.Synopsis | Should Be $originalHelpObject.Synopsis - } - - $originalSyntax = $originalHelpObject.syntax.syntaxItem - $generatedSyntax = $generatedHelpObject.Syntax.syntaxItem - - It 'generate correct Syntax count' { - $generatedSyntax.Count | Should Be $originalSyntax.Count - # this check is too strict, we will do it one-by-one - #($generatedHelpObject.syntax | Out-String) | Should Be ($originalHelpObject.syntax | Out-String) - } - - It 'generate correct InputObject in syntax' { - $originalInputObject = $originalSyntax[0].parameter | Where-Object {$_.name -eq 'InputObject'} - $generatedInputObject = $originalSyntax[0].parameter | Where-Object {$_.name -eq 'InputObject'} - ($originalInputObject | Out-String) | Should Be ($generatedInputObject | Out-String) - } - - It 'generate correct description' { - $generatedHelpObject.description.Count | Should Be $originalHelpObject.description.Count - 0..($generatedHelpObject.description.Count - 1) | ForEach-Object { - $generatedHelpObject.description[$_].ToString() | Should Be $originalHelpObject.description[$_].ToString() - } - } - - It 'generate correct example count' { - $generatedHelpObject.examples.example.Count | Should Be $originalHelpObject.examples.example.Count - } - - Context 'examples' { - # there is unredable character in EXAMPLE 6 in Add-Member -Force - # this '-' before force could be screwed up - 0..($generatedHelpObject.examples.example.Count - 1) | ForEach-Object { - It ('generate correct example ' + ($generatedHelpObject.examples.example[$_].title)) -Skip:($_ -eq 5) { - - $exampleExtractionRegex = '^(-| ){0,}(?<title>([^\f\n\r\t\v\x85\p{Z}-][^\f\n\r\t\v\x85]+[^\f\n\r\t\v\x85\p{Z}-]))(-| ){0,}(\r|\n){1,}(?<body>(\S|\s)+)'; - $generatedMatches = [Regex]::Match(($generatedHelpObject.examples.example[$_] | Out-String).Trim(), $exampleExtractionRegex) - $originalMatches = [Regex]::Match(($originalHelpObject.examples.example[$_] | Out-String).Trim(), $exampleExtractionRegex) - - # Confirm match completed successfully - $generatedMatches.Success | Should Be $True - $originalMatches.Success | Should Be $True - - # Match clean title and clean body seperately - $generatedMatches.Groups['title'].Value | Should Be $originalMatches.Groups['title'].Value - $generatedMatches.Groups['body'].Value | Should Be $originalMatches.Groups['body'].Value - } - } - } - - Context 'parameters' { - It 'generate correct parameters count' { - $originalParameters = $originalHelpObject.parameters.parameter - $generatedHelpObject.parameters.parameter.Count | Should Be $originalParameters.Count - } - - 0..($generatedHelpObject.parameters.parameter.Count - 1) | ForEach-Object { - $genParam = $generatedHelpObject.parameters.parameter[$_] - $name = $genParam.name - # By default is empty, set default value of 'False' if parametr is empty and type is 'SwitchParameter' - # Otherwise, set default value of 'None' if parameter is empty - if([String]::IsNullOrEmpty($originalHelpObject.parameters.parameter[$_].defaultValue) -and $originalHelpObject.parameters.parameter[$_].type.name.Equals("SwitchParameter")) - { - $originalHelpObject.parameters.parameter[$_].defaultValue = "False" - } - elseif([String]::IsNullOrEmpty($originalHelpObject.parameters.parameter[$_].defaultValue)) - { - $originalHelpObject.parameters.parameter[$_].defaultValue = "None" - } - $origParam = $originalHelpObject.parameters.parameter | Where-Object {$_.Name -eq $name} - # skip because of unclearaty of RequiredValue meaning for - $skip = @('Value', 'SecondValue', 'InformationVariable', 'InformationAction') -contains $name - It ('generate correct parameter ' + ($name)) -Skip:$skip { - ($genParam | Out-String).TrimEnd() | Should Be ($origParam | Out-String).TrimEnd() - } - } - } - - It 'generate correct relatedLinks' { - ($generatedHelpObject.relatedLinks | Out-String) | Should Be ($originalHelpObject.relatedLinks | Out-String) - } - - It 'generate correct inputTypes' { - ($generatedHelpObject.inputTypes.inputType.description | Out-String).Trim() | Should Be ( - $originalHelpObject.inputTypes.inputType.description | Out-String).Trim() - } - - It 'generate correct returnValues' { - ($generatedHelpObject.returnValues.returnValue.description | Out-String).Trim() | Should Be ( - $originalHelpObject.returnValues.returnValue.description | Out-String).Trim() - } - - # TODO: rest of properties!! -} - #> -function OutFileAndStripped -{ - param([string]$path, [string]$content) - - $strippedContent = ((((($content) -replace '\[<', '<') -replace '\[<', '<') -replace '>\]', '>') -replace '>\]', '>') - Set-Content -Path "$path.stripped" -Value $strippedContent - Set-Content -Path $path -Value $content -} - -Describe 'Microsoft.PowerShell.Core (SMA) help' { - - Context 'produce the real help' { - $textOutputFile = "$outFolder\SMA.original.txt" - $help = Get-HelpPreview $pshome\en-US\System.Management.Automation.dll-Help.xml | Out-String - OutFileAndStripped -path $textOutputFile -content $help - } - - # parameters for New-Markdown - @( - - [psobject]@{ - MamlFile = "$pshome\en-US\System.Management.Automation.dll-Help.xml" - OutputFolder = "$outFolder\sma-maml" - Force = $true - ConvertNotesToList = $true - ConvertDoubleDashLists = $true - }, - - [psobject]@{ - module = "Microsoft.PowerShell.Core" - OutputFolder = "$outFolder\sma-model" - Force = $true - } - - ) | ForEach-Object { - - $newMarkdownArgs = $_ - - Context "Output SMA into $($newMarkdownArgs.OutputFolder)" { - $mdFiles = New-MarkdownHelp @newMarkdownArgs - $IsMaml = (Split-Path -Leaf $newMarkdownArgs.OutputFolder) -eq 'sma-maml' - $SkipNotPresent = (-not $IsMaml) -and ($MyIsLinux -or $MyIsMacOS) - - It 'transforms Markdown to MAML with no errors' { - $generatedMaml = $mdFiles | New-ExternalHelp -Verbose -OutputPath $newMarkdownArgs.OutputFolder -Force - $generatedMaml.Name | Should Be 'System.Management.Automation.dll-Help.xml' - - # add artifacts to out - $textOutputFile = Join-Path $newMarkdownArgs.OutputFolder 'SMA.generated.txt' - $help = Get-HelpPreview $generatedMaml.FullName | Out-String - OutFileAndStripped -path $textOutputFile -content $help - } - - # this our regression suite for SMA - $generatedHelp = Get-HelpPreview (Join-Path $newMarkdownArgs.OutputFolder 'System.Management.Automation.dll-Help.xml') - - It 'has right number of outputs for Get-Help' { - $h = $generatedHelp | Where-Object {$_.Name -eq 'Get-Help'} - ($h.returnValues.returnValue | Measure-Object).Count | Should Be 3 - } - - It 'Get-Help has ValidateSet entry in syntax block' { - $h = $generatedHelp | Where-Object {$_.Name -eq 'Get-Help'} - $validateString = '{Alias | Cmdlet | Provider | General' - ($h.syntax | Out-String).Contains($validateString) | Should Be $true - } - - It 'has right type for New-PSTransportOption -IdleTimeoutSec' -Skip:$IsMaml { - $h = $generatedHelp | Where-Object {$_.Name -eq 'New-PSTransportOption'} - $param = $h.parameters.parameter | Where-Object {$_.Name -eq 'IdleTimeoutSec'} - $param.type.name | Should Be 'Int32' - } - - It 'Enter-PSHostProcess first argument is not -AppDomainName in all syntaxes' -Skip:$SkipNotPresent { - $h = $generatedHelp | Where-Object {$_.Name -eq 'Enter-PSHostProcess'} - $h | Should Not BeNullOrEmpty - $h.syntax.syntaxItem | ForEach-Object { - $_.parameter.Name[0] | Should Not Be 'AppDomainName' - } - } - - It 'preserve a list in Disconnect-PSSession -OutputBufferingMode' -Skip { - $listItemMark = '- ' - $newLineX3 = [System.Environment]::NewLine * 3 - $h = $generatedHelp | Where-Object {$_.Name -eq 'Disconnect-PSSession'} - $param = $h.parameters.parameter | Where-Object {$_.Name -eq 'OutputBufferingMode'} - ($param.description | Out-String).Contains("clear.$newLineX3$($listItemMark)Drop. When") | Should Be $true - ($param.description | Out-String).Contains("discarded.$newLineX3$($listItemMark)None. No") | Should Be $true - } - - if (-not $IsMaml) - { - It 'preserve formatting for Connect-PSSession NOTES' -Skip:$SkipNotPresent { - - # We are cheating a little bit here :( - function NormalizeEndings - { - param( - [string]$text - ) - - $text2 = ($text -replace "`r","") - [Regex]::Replace($text2, "(`n *)+", "`n") - } - - $h = $generatedHelp | Where-Object {$_.Name -eq 'Connect-PSSession'} - $expected = NormalizeEndings ( (Get-Help Connect-PSSession).alertSet | Out-String ) - NormalizeEndings ( $h.alertSet | Out-String ) | Should Be $expected - } - } - } - } -} diff --git a/v1/test/Pester/PlatyPs.Tests.ps1 b/v1/test/Pester/PlatyPs.Tests.ps1 deleted file mode 100644 index 139051a7..00000000 --- a/v1/test/Pester/PlatyPs.Tests.ps1 +++ /dev/null @@ -1,1615 +0,0 @@ -Set-StrictMode -Version latest -$ErrorActionPreference = 'Stop' - -$root = (Resolve-Path $PSScriptRoot\..\..).Path -$outFolder = "$root\out" -$moduleFolder = "$outFolder\platyPS" - -#Import-Module $moduleFolder -Force -$MyIsLinux = Get-Variable -Name IsLinux -ValueOnly -ErrorAction SilentlyContinue -$MyIsMacOS = Get-Variable -Name IsMacOS -ValueOnly -ErrorAction SilentlyContinue -$global:IsUnix = $MyIsLinux -or $MyIsMacOS - -#Import-LocalizedData -BindingVariable LocalizedData -BaseDirectory $moduleFolder -FileName platyPS.Resources.psd1 - -Describe 'New-MarkdownHelp' { - function normalizeEnds([string]$text) - { - $text -replace "`r`n?|`n", "`r`n" - } - - Context 'errors' { - It 'throw when cannot find module' { - { New-MarkdownHelp -Module __NON_EXISTING_MODULE -OutputFolder TestDrive:\ } | - Should Throw ($LocalizedData.ModuleNotFound -f '__NON_EXISTING_MODULE') - } - - It 'throw when cannot find module' { - { New-MarkdownHelp -command __NON_EXISTING_COMMAND -OutputFolder TestDrive:\ } | - Should Throw ($LocalizedData.CommandNotFound -f '__NON_EXISTING_COMMAND') - } - } - - Context 'metadata' { - It 'generates passed metadata' { - $file = New-MarkdownHelp -metadata @{ - FOO = 'BAR' - } -command New-MarkdownHelp -OutputFolder TestDrive:\ - - $h = Get-MarkdownMetadata $file - $h['FOO'] | Should Be 'BAR' - } - - It 'respects -NoMetadata' { - $file = New-MarkdownHelp -command New-MarkdownHelp -OutputFolder TestDrive:\ -NoMetadata -Force - Get-MarkdownMetadata $file.FullName | Should Be $null - } - - It 'errors on -NoMetadata and -Metadata' { - { New-MarkdownHelp -command New-MarkdownHelp -OutputFolder TestDrive:\ -NoMetadata -Force -Metadata @{} } | - Should Throw $LocalizedData.NoMetadataAndMetadata - } - } - - Context 'encoding' { - $file = New-MarkdownHelp -command New-MarkdownHelp -OutputFolder TestDrive:\ -Force -Encoding ([System.Text.Encoding]::UTF32) - $content = $file | Get-Content -Encoding UTF32 -Raw - Get-MarkdownMetadata -Markdown $content | Should Not Be $null - } - - Context 'from platyPS module' { - It 'creates few help files for platyPS' { - $files = New-MarkdownHelp -Module PlatyPS -OutputFolder TestDrive:\platyPS -Force - ($files | Measure-Object).Count | Should BeGreaterThan 4 - } - } - - Context 'from module' { - try - { - New-Module -Name PlatyPSTestModule -ScriptBlock { - function Get-AAAA - { - - } - - function Get-AdvancedFn - { - [CmdletBinding()] - param ( - - ) - } - - function Get-SimpleFn - { - param ( - - ) - } - - function Set-BBBB - { - - } - - - if (-not $global:IsUnix) { - # just declaring workflow is a parse-time error on unix - Invoke-Expression "Workflow FromCommandWorkflow {}" - Export-ModuleMember -Function 'FromCommandWorkflow' - } - - # Set-Alias and New-Alias provide two different results - # when `Get-Command -module Foo` is used to list commands. - Set-Alias aaaaalias Get-AAAA - Set-Alias bbbbalias Get-BBBB - - New-Alias -Name 'Fork-AAAA' -Value 'Get-AAAA' - - Export-ModuleMember -Alias Fork-AAAA - Export-ModuleMember -Alias aaaaalias - Export-ModuleMember -Alias bbbbalias - Export-ModuleMember -Function 'Get-AAAA','Get-AdvancedFn','Get-SimpleFn' - - } | Import-Module -Force - - $files = New-MarkdownHelp -Module PlatyPSTestModule -OutputFolder TestDrive:\PlatyPSTestModule -Force - } - finally - { - Remove-Module PlatyPSTestModule -ErrorAction SilentlyContinue - } - - It 'generates markdown files only for exported functions' -Skip:$IsUnix { - ($files | Measure-Object).Count | Should Be 4 - $files.Name | Should -BeIn 'Get-AAAA.md','Get-AdvancedFn.md','Get-SimpleFn.md','FromCommandWorkflow.md' - } - - It 'generates markdown that includes CommonParameters in advanced functions' { - ($files | Where-Object -FilterScript { $_.Name -eq 'Get-AdvancedFn.md' }).FullName | Should -FileContentMatch '### CommonParameters' - } - - It 'generates markdown that excludes CommonParameters from simple functions' { - ($files | Where-Object -FilterScript { $_.Name -eq 'Get-SimpleFn.md' }).FullName | Should -FileContentMatch -Not '### CommonParameters' - } - - It 'generates markdown for workflows with CommonParameters' -Skip:$IsUnix { - ($files | Where-Object -FilterScript { $_.Name -eq 'FromCommandWorkflow.md' }).FullName | Should -FileContentMatch '### CommonParameters' - } - } - - Context 'from command' { - It 'creates 2 markdown files from command names' { - $files = New-MarkdownHelp -Command @('New-MarkdownHelp', 'Get-MarkdownMetadata') -OutputFolder TestDrive:\commands -Force - ($files | Measure-Object).Count | Should Be 2 - } - } - - Context 'from external script' { - It 'fully qualified path' { - $SeedData = @" -<# -.SYNOPSIS - Synopsis Here. - -.DESCRIPTION - Description Here. - -.INPUTS - None - -.OUTPUTS - None - -.EXAMPLE - .\Invoke-HelloWorld.ps1 - -#> - -Write-Host 'Hello World!' -"@ - Set-Content -Value $SeedData -Path TestDrive:\Invoke-HelloWorld.ps1 -NoNewline - $files = New-MarkdownHelp -Command "TestDrive:\Invoke-HelloWorld.ps1" -OutputFolder TestDrive:\output -Force - ($files | Measure-Object).Count | Should Be 1 - } - It 'relative path' { - $SeedData = @" -<# -.SYNOPSIS - Synopsis Here. - -.DESCRIPTION - Description Here. - -.INPUTS - None - -.OUTPUTS - None - -.EXAMPLE - .\Invoke-HelloWorld.ps1 - -#> - -Write-Host 'Hello World!' -"@ - Set-Content -Value $SeedData -Path TestDrive:\Invoke-HelloWorld.ps1 -NoNewline - $Location = Get-Location - Set-Location TestDrive:\ - $files = New-MarkdownHelp -Command "TestDrive:\Invoke-HelloWorld.ps1" -OutputFolder TestDrive:\output -Force - Set-Location $Location - ($files | Measure-Object).Count | Should Be 1 - } - } - Context 'AlphabeticParamsOrder' { - function global:Get-Alpha - { - param( - [Switch] - [Parameter(Position = 1)] - $WhatIf, - [string] - [Parameter(Position = 2)] - $CCC, - [Parameter(Position = 0)] - [uint64] - $First, - [string] - $AAA, - [Parameter(Position = 3)] - [uint64] - $Skip, - [string] - $BBB, - [Parameter(Position = 4)] - [switch] - $IncludeTotalCount, - [Switch] - $Confirm - ) - } - - It 'uses alphabetic order when specified' { - - $expectedOrder = normalizeEnds @' -### -AAA -### -BBB -### -CCC -### -Confirm -### -WhatIf -### -IncludeTotalCount -### -Skip -### -First - -'@ - $files = New-MarkdownHelp -Command Get-Alpha -OutputFolder TestDrive:\alpha -Force -AlphabeticParamsOrder - ($files | Measure-Object).Count | Should Be 1 - normalizeEnds (Get-Content $files | Where-Object {$_.StartsWith('### -')} | Out-String) | Should Be $expectedOrder - } - } - - Context 'Online version link' { - - function global:Test-PlatyPSFunction { - <# - .LINK - http://www.fabrikam.com/extension.html - #> - } - - @('https://github.com/PowerShell/platyPS', 'http://www.fabrikam.com/extension.html', $null) | ForEach-Object { - $uri = $_ - It "generates passed online url '$uri'" { - $a = @{ - command = 'Test-PlatyPSFunction' - OutputFolder = 'TestDrive:\' - Force = $true - OnlineVersionUrl = $uri - } - - $file = New-MarkdownHelp @a - $maml = $file | New-ExternalHelp -OutputPath "TestDrive:\" -Force - $help = Get-HelpPreview -Path $maml - $link = $help.relatedLinks.navigationLink - if ($uri) { - if ($uri -eq 'http://www.fabrikam.com/extension.html') { - ($link | Measure-Object).Count | Should Be 1 - $link[0].linkText | Should Be $uri - $link[0].uri | Should Be 'http://www.fabrikam.com/extension.html' - } - else { - ($link | Measure-Object).Count | Should Be 2 - $link[0].linkText | Should Be 'Online Version:' - $link[0].uri | Should Be $uri - } - } - } - } - } - - Context 'Generates well-known stub descriptions for parameters' { - function global:Test-PlatyPSFunction { - param( - [string]$Foo, - [switch]$Confirm, - [switch]$WhatIf, - [switch]$IncludeTotalCount, - [uint64]$Skip, - [uint64]$First - ) - } - - $file = New-MarkdownHelp -Command Test-PlatyPSFunction -OutputFolder TestDrive:\ -Force -AlphabeticParamsOrder - $maml = $file | New-ExternalHelp -OutputPath "TestDrive:\" -Force - $help = Get-HelpPreview -Path $maml - - It 'generates well-known stub descriptions for -WhatIf' { - $param = $help.parameters.parameter | Where-Object { $_.Name -eq 'WhatIf' } - $param.description.text | Should Be $LocalizedData.WhatIf - } - - It 'generates well-known stub descriptions for -Confirm' { - $param = $help.parameters.parameter | Where-Object { $_.Name -eq 'Confirm' } - $param.description.text | Should Be $LocalizedData.Confirm - } - - It 'generates well-known stub descriptions for -IncludeTotalCount' { - $param = $help.parameters.parameter | Where-Object { $_.Name -eq 'IncludeTotalCount' } - $param.description.text | Should Be $LocalizedData.IncludeTotalCount - } - - It 'generates well-known stub descriptions for -Skip' { - $param = $help.parameters.parameter | Where-Object { $_.Name -eq 'Skip' } - $param.description.text | Should Be $LocalizedData.Skip - } - - It 'generates well-known stub descriptions for -First' { - $param = $help.parameters.parameter | Where-Object { $_.Name -eq 'First' } - $param.description.text | Should Be $LocalizedData.First - } - - It 'generates well-known stub descriptions for -Foo' { - $param = $help.parameters.parameter | Where-Object { $_.Name -eq 'Foo' } - $param.description.text | Should Be ($LocalizedData.ParameterDescription -f 'Foo') - } - } - - Context 'Generated markdown features: comment-based help' { - function global:Test-PlatyPSFunction - { - # comment-based help template from https://technet.microsoft.com/en-us/library/hh847834.aspx - - <# - .SYNOPSIS - Adds a file name extension to a supplied name. - - .DESCRIPTION - Adds a file name extension to a supplied name. - Takes any strings for the file name or extension. - - .PARAMETER Second - Second parameter help description - - .OUTPUTS - System.String. Add-Extension returns a string with the extension or file name. - - .EXAMPLE - PS C:\> Test-PlatyPSFunction "File" - File.txt - - .EXAMPLE - PS C:\> Test-PlatyPSFunction "File" -First "doc" - File.doc - - .LINK - http://www.fabrikam.com/extension.html - - .LINK - Set-Item - #> - - param( - [Switch]$Common, - [Parameter(ParameterSetName="First", HelpMessage = 'First parameter help description')] - [string]$First, - [Parameter(ParameterSetName="Second")] - [string]$Second - ) - } - - $file = New-MarkdownHelp -Command Test-PlatyPSFunction -OutputFolder TestDrive:\testAll1 -Force - $content = Get-Content $file - - It 'generates markdown with correct parameter set names' { - ($content | Where-Object {$_ -eq 'Parameter Sets: (All)'} | Measure-Object).Count | Should Be 1 - ($content | Where-Object {$_ -eq 'Parameter Sets: First'} | Measure-Object).Count | Should Be 1 - ($content | Where-Object {$_ -eq 'Parameter Sets: Second'} | Measure-Object).Count | Should Be 1 - } - - It 'generates markdown with correct synopsis' { - ($content | Where-Object {$_ -eq 'Adds a file name extension to a supplied name.'} | Measure-Object).Count | Should Be 2 - } - - It 'generates markdown with correct help description specified by HelpMessage attribute' { - ($content | Where-Object {$_ -eq 'First parameter help description'} | Measure-Object).Count | Should Be 1 - } - - It 'generates markdown with correct help description specified by comment-based help' { - ($content | Where-Object {$_ -eq 'Second parameter help description'} | Measure-Object).Count | Should Be 1 - } - - It 'generates markdown with placeholder for parameter with no description' { - ($content | Where-Object {$_ -eq ($LocalizedData.ParameterDescription -f 'Common')} | Measure-Object).Count | Should Be 1 - } - } - - Context 'Generated markdown features: no comment-based help' { - function global:Test-PlatyPSFunction - { - # there is a help-engine behavior difference for functions with comment-based help (or maml help) - # and no-comment based help, we test both - param( - [Switch]$Common, - [Parameter(ParameterSetName="First", HelpMessage = 'First parameter help description')] - [string]$First, - [Parameter(ParameterSetName="Second")] - [string]$Second - ) - } - - $file = New-MarkdownHelp -Command Test-PlatyPSFunction -OutputFolder TestDrive:\testAll2 -Force - $content = Get-Content $file - - It 'generates markdown with correct synopsis placeholder' { - ($content | Where-Object {$_ -eq $LocalizedData.Synopsis} | Measure-Object).Count | Should Be 1 - } - - It 'generates markdown with correct help description specified by HelpMessage attribute' { - ($content | Where-Object {$_ -eq 'First parameter help description'} | Measure-Object).Count | Should Be 1 - } - - It 'generates markdown with placeholder for parameter with no description' { - ($content | Where-Object {$_ -eq ($LocalizedData.ParameterDescription -f 'Common')} | Measure-Object).Count | Should Be 1 - } - } - - Context 'Dynamic parameters' { - - function global:Test-DynamicParameterSet { - [CmdletBinding()] - [OutputType()] - - Param ( - [Parameter( - ParameterSetName = 'Static' - )] - [Switch] - $StaticParameter - ) - - DynamicParam { - $dynamicParamAttributes = New-Object -TypeName System.Management.Automation.ParameterAttribute -Property @{ - ParameterSetName = 'Dynamic' - } - $dynamicParamCollection = New-Object -TypeName System.Collections.ObjectModel.Collection[System.Attribute] - $dynamicParamCollection.Add($dynamicParamAttributes) - $dynamicParam = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameter -ArgumentList ('DynamicParameter', [Switch], $dynamicParamCollection) - $dictionary = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameterDictionary - $dictionary.Add('DynamicParameter', $dynamicParam) - return $dictionary - } - - Process { - Write-Output -InputObject $PSCmdlet.ParameterSetName - } - } - - It "generates DynamicParameter" { - $a = @{ - command = 'Test-DynamicParameterSet' - OutputFolder = 'TestDrive:\' - } - - $file = New-MarkdownHelp @a - $maml = $file | New-ExternalHelp -OutputPath "TestDrive:\" - $help = Get-HelpPreview -Path $maml - $help.Syntax.syntaxItem.Count | Should Be 2 - $dynamicParam = $help.parameters.parameter | Where-Object {$_.name -eq 'DynamicParameter'} - ($dynamicParam | Measure-Object).Count | Should Be 1 - } - } - - Context 'Module Landing Page'{ - - $OutputFolder = "TestDrive:\LandingPageMD\" - $OutputFolderReadme = 'TestDrive:\LandingPageMD-ReadMe\Readme.md' - - New-Item -ItemType Directory $OutputFolder - - - It "generates a landing page from Module"{ - - New-MarkdownHelp -Module PlatyPS -OutputFolder $OutputFolder -WithModulePage -Force - - $LandingPage = Get-ChildItem (Join-Path $OutputFolder PlatyPS.md) - - $LandingPage | Should Not Be $null - - } - - It "generates a landing page from MAML"{ - - New-MarkdownHelp -MamlFile (Get-ChildItem "$outFolder\platyPS\en-US\platy*xml") ` - -OutputFolder $OutputFolder ` - -WithModulePage ` - -ModuleName "PlatyPS" ` - -Force - - $LandingPage = Get-ChildItem (Join-Path $OutputFolder PlatyPS.md) - - $LandingPage | Should Not Be $null - - } - - it 'generate a landing page from Module with parameter ModulePagePath' { - New-MarkdownHelp -Module PlatyPS -OutputFolder $OutputFolder -WithModulePage -ModulePagePath $OutputFolderReadme -Force - - $LandingPage = Test-Path -Path $OutputFolderReadme - $LandingPage | Should Not Be $null - } - - } - - Context 'Full Type Name' { - function global:Get-Alpha - { - param( - [Switch] - [Parameter(Position=1)] - $WhatIf, - [string] - [Parameter(Position=2)] - $CCC, - [System.Nullable`1[System.Int32]] - [Parameter(Position=3)] - $ddd - ) - } - - It 'use full type name when specified' { - $expectedParameters = normalizeEnds @' -Type: System.String -Type: System.Nullable`1[System.Int32] -Type: System.Management.Automation.SwitchParameter - -'@ - $expectedSyntax = normalizeEnds @' -Get-Alpha [-WhatIf] [[-CCC] <String>] [[-ddd] <Int32>] [<CommonParameters>] - -'@ - - $files = New-MarkdownHelp -Command Get-Alpha -OutputFolder TestDrive:\alpha -Force -AlphabeticParamsOrder -UseFullTypeName - ($files | Measure-Object).Count | Should Be 1 - normalizeEnds(Get-Content $files | Where-Object {$_.StartsWith('Type: ')} | Out-String) | Should Be $expectedParameters - normalizeEnds(Get-Content $files | Where-Object {$_.StartsWith('Get-Alpha')} | Out-String) | Should Be $expectedSyntax - } - - It 'not use full type name when specified' { - $expectedParameters = normalizeEnds @' -Type: String -Type: Int32 -Type: SwitchParameter - -'@ - $expectedSyntax = normalizeEnds @' -Get-Alpha [-WhatIf] [[-CCC] <String>] [[-ddd] <Int32>] [<CommonParameters>] - -'@ - - $files = New-MarkdownHelp -Command Get-Alpha -OutputFolder TestDrive:\alpha -Force -AlphabeticParamsOrder - ($files | Measure-Object).Count | Should Be 1 - normalizeEnds(Get-Content $files | Where-Object {$_.StartsWith('Type: ')} | Out-String) | Should Be $expectedParameters - normalizeEnds(Get-Content $files | Where-Object {$_.StartsWith('Get-Alpha')} | Out-String) | Should Be $expectedSyntax - } - } - - Context 'DontShow parameter' { - BeforeAll { - function global:Test-DontShowParameter { - [CmdletBinding()] - [OutputType()] - - Param ( - [Parameter()] - [Switch] - $ShowAll, - - [Parameter(DontShow)] - [Switch] - $DontShowAll, - - [Parameter(ParameterSetName = 'Set1', DontShow)] - [Parameter(ParameterSetName = 'Set2')] - [Switch] - $DontShowSet1, - - [Parameter(ParameterSetName = 'Set1', DontShow)] - [Parameter(ParameterSetName = 'Set2', DontShow)] - [Switch] - $DontShowSetAll - ) - - Process { - Write-Output -InputObject $PSCmdlet.ParameterSetName - } - } - - $a = @{ - command = 'Test-DontShowParameter' - OutputFolder = 'TestDrive:\' - } - - $fileWithoutDontShowSwitch = New-MarkdownHelp @a -Force - $file = New-MarkdownHelp @a -ExcludeDontShow -Force - - $maml = $file | New-ExternalHelp -OutputPath "TestDrive:\" - $help = Get-HelpPreview -Path $maml - $mamlModelObject = & (Get-Module platyPS) { GetMamlObject -Cmdlet "Test-DontShowParameter" } - - $updatedFile = Update-MarkdownHelp -Path $fileWithoutDontShowSwitch -ExcludeDontShow - $null = New-Item -ItemType Directory "$TestDrive\UpdateMarkdown" - $updatedMaml = $file | New-ExternalHelp -OutputPath "TestDrive:\UpdateMarkdown" - $updatedHelp = Get-HelpPreview -Path $updatedMaml - $updateMamlModelObject = & (Get-Module platyPS) { GetMamlObject -Cmdlet "Test-DontShowParameter" } - } - - Context "New-MarkdownHelp with -ExcludeDontShow" { - It "includes ShowAll" { - $showAll = $help.parameters.parameter | Where-Object {$_.name -eq 'ShowAll'} - ($showAll | Measure-Object).Count | Should Be 1 - } - - It "excludes DontShowAll" { - $dontShowAll = $help.parameters.parameter | Where-Object {$_.name -eq 'DontShowAll'} - ($dontShowAll | Measure-Object).Count | Should Be 0 - } - - It 'includes DontShowSet1 excludes Set1' -Skip { - $dontShowSet1 = $help.parameters.parameter | Where-Object {$_.name -eq 'DontShowSet1'} - ($dontShowSet1 | Measure-Object).Count | Should Be 1 - - $set1 = $mamlModelObject.Syntax | Where-Object {$_.ParameterSetName -eq 'Set1'} - ($set1 | Measure-Object).Count | Should Be 0 - } - - It 'excludes DontShowSetAll includes Set2' { - $dontShowAll = $help.parameters.parameter | Where-Object {$_.name -eq 'DontShowSetAll'} - ($dontShowAll | Measure-Object).Count | Should Be 0 - - $set2 = $mamlModelObject.Syntax | Where-Object {$_.ParameterSetName -eq 'Set2'} - ($set2 | Measure-Object).Count | Should Be 1 - } - } - - Context "Update-MarkdownHelp with -ExcludeDontShow" { - It "includes ShowAll" { - $showAll = $updatedHelp.parameters.parameter | Where-Object {$_.name -eq 'ShowAll'} - ($showAll | Measure-Object).Count | Should Be 1 - } - - It "excludes DontShowAll" { - $dontShowAll = $updatedHelp.parameters.parameter | Where-Object {$_.name -eq 'DontShowAll'} - ($dontShowAll | Measure-Object).Count | Should Be 0 - } - - It 'includes DontShowSet1 excludes Set1' -Skip { - $dontShowSet1 = $updatedHelp.parameters.parameter | Where-Object {$_.name -eq 'DontShowSet1'} - ($dontShowSet1 | Measure-Object).Count | Should Be 1 - - $set1 = $mamlModelObject.Syntax | Where-Object {$_.ParameterSetName -eq 'Set1'} - ($set1 | Measure-Object).Count | Should Be 0 - } - - It 'excludes DontShowSetAll includes Set2' { - $dontShowAll = $updatedHelp.parameters.parameter | Where-Object {$_.name -eq 'DontShowSetAll'} - ($dontShowAll | Measure-Object).Count | Should Be 0 - - $set2 = $mamlModelObject.Syntax | Where-Object {$_.ParameterSetName -eq 'Set2'} - ($set2 | Measure-Object).Count | Should Be 1 - } - } - - Context 'SupportsWildCards attribute tests' { - BeforeAll { - - function global:Test-WildCardsAttribute { - param ( - [Parameter()] - [SupportsWildcards()] - [string] $Name, - - [Parameter()] - [string] $NameNoWildCard - ) - } - - $file = New-MarkdownHelp -Command 'Test-WildCardsAttribute' -OutputFolder "$TestDrive\NewMarkDownHelp" - $maml = $file | New-ExternalHelp -OutputPath "$TestDrive\NewMarkDownHelp" - $help = Get-HelpPreview -Path $maml - } - - It 'sets accepts wildcards property on parameters as expected' { - $help.parameters.parameter | Where-Object { $_.Name -eq 'Name' } | ForEach-Object { $_.globbing -eq 'true'} - $help.parameters.parameter | Where-Object { $_.Name -eq 'NameNoWildCard' } | ForEach-Object { $_.globbing -eq 'false'} - } - } - } -} - - -############################################################### -############################################################### - - -Describe 'New-ExternalHelp' { - BeforeAll { - function global:Test-OrderFunction { - param ([Parameter(Position=3)]$Third, [Parameter(Position=1)]$First, [Parameter()]$Named) - $First - $Third - $Named - } - $file = New-MarkdownHelp -Command 'Test-OrderFunction' -OutputFolder $TestDrive -Force - $maml = $file | New-ExternalHelp -OutputPath "$TestDrive\TestOrderFunction.xml" -Force - } - - It "generates right order for syntax" { - $help = Get-HelpPreview -Path $maml - ($help.Syntax.syntaxItem | Measure-Object).Count | Should Be 1 - $names = $help.Syntax.syntaxItem.parameter.Name - ($names | Measure-Object).Count | Should Be 3 - $names[0] | Should Be 'First' - $names[1] | Should Be 'Third' - $names[2] | Should Be 'Named' - } - - It "checks that xmlns 'http://msh' is present" { - $xml = [xml] (Get-Content (Join-Path $TestDrive 'TestOrderFunction.xml')) - $xml.helpItems.namespaceuri | Should Be 'http://msh' - } -} - -Describe 'New-ExternalHelp -ErrorLogFile' { - BeforeAll { - function global:Test-OrderFunction { - param ([Parameter(Position = 3)]$Third, [Parameter(Position = 1)]$First, [Parameter()]$Named) - $First - $Third - $Named - } - - try { - # Don't add metadata so the file has an error - $file = New-MarkdownHelp -Command 'Test-OrderFunction' -OutputFolder $TestDrive -Force -NoMetadata - $maml = $file | New-ExternalHelp -OutputPath "$TestDrive\TestOrderFunction.xml" -ErrorLogFile "$TestDrive\warningsAndErrors.json" -Force - } - catch { - # Ignore the error. I just needed an error to write to the log file. - # If I don't catch this the test will fail. - } - } - - It "generates error log file" { - Test-Path "$TestDrive\warningsAndErrors.json" | Should Be $true - } -} - -Describe 'New-ExternalHelp -ApplicableTag for cmdlet level' { - BeforeAll { - function global:Test-Applicable12 {} - function global:Test-ApplicableNone {} - function global:Test-Applicable32 {} - function global:Test-Applicable4 {} - } - - It 'ignores cmdlet when applicable tag doesn''t match' { - $files = @() - $files += New-MarkdownHelp -Metadata @{ applicable = 'tag 1, tag 2'} -Command Test-Applicable12 -OutputFolder $TestDrive -Force -WarningAction SilentlyContinue - $files += New-MarkdownHelp -Metadata @{ applicable = 'tag 3, tag 2'} -Command Test-Applicable32 -OutputFolder $TestDrive -Force -WarningAction SilentlyContinue - $files += New-MarkdownHelp -Command Test-ApplicableNone -OutputFolder $TestDrive -Force -WarningAction SilentlyContinue - $files += New-MarkdownHelp -Metadata @{ applicable = 'tag 4'} -Command Test-Applicable4 -OutputFolder $TestDrive -Force -WarningAction SilentlyContinue - - $maml = $files | New-ExternalHelp -ApplicableTag @('tag 1', 'tag 4') -OutputPath "$TestDrive\TestApplicable.xml" -Force - $help = Get-HelpPreview -Path $maml - ($help | Measure-Object).Count | Should Be 3 - $names = $help.Name - $names[0] | Should Be 'Test-Applicable12' - $names[1] | Should Be 'Test-ApplicableNone' - $names[2] | Should Be 'Test-Applicable4' - } -} - -Describe 'New-ExternalHelp -ApplicableTag for parameters level' { - It 'ignores parameters when applicable tag doesn''t match' { - $md = @' ---- -schema: 2.0.0 ---- - -# Get-Foo -## PARAMETERS - -### -P1 - -```yaml -Type: String -Applicable: tag 1, tag 2 -``` - -### -P2 - -```yaml -Type: String -Applicable: tag 3 -``` - -### -P3 - -```yaml -Type: String -``` - -### -P4 - -```yaml -Type: String -Applicable: tag 4 -``` -'@ - $path = "$outFolder\Get-Foo.md" - Set-Content -Path $path -Value $md - $maml = $path | New-ExternalHelp -ApplicableTag @('tag 1', 'tag 4') -OutputPath "$TestDrive\TestApplicable.xml" -Force - $help = Get-HelpPreview -Path $maml - $names = $help.Parameters.parameter.Name - ($names | Measure-Object).Count | Should Be 3 - $names[0] | Should Be 'P1' - $names[1] | Should Be 'P3' - $names[2] | Should Be 'P4' - } -} - -if (-not $global:IsUnix) { -#region PS Objects to MAML Model Tests - Describe 'Get-Help & Get-Command on Add-Computer to build MAML Model Object' { - - Context 'Add-Computer' { - - It 'Checks that Help Exists on Computer Running Tests' { - - $Command = Get-Command Add-Computer - $HelpFileName = Split-Path $Command.HelpFile -Leaf - $foundHelp = @() - $paths = $env:PsModulePath.Split(';') - foreach($path in $paths) - { - $path = Split-Path $path -Parent - $foundHelp += Get-ChildItem -ErrorAction SilentlyContinue -Path $path -Recurse | - Where-Object { $_.Name -like "*$HelpFileName"} | Select-Object Name - } - - $foundHelp.Count | Should BeGreaterThan 0 - } - - # call non-exported function in the module scope - $mamlModelObject = & (Get-Module platyPS) { GetMamlObject -Cmdlet "Add-Computer" } - - It 'Validates attributes by checking several sections of the single attributes for Add-Computer' { - - $mamlModelObject.Name | Should be "Add-Computer" - $mamlModelObject.Synopsis.Text | Should be "Add the local computer to a domain or workgroup." - $mamlModelObject.Description.Text.Substring(0,137) | Should be 'The `Add-Computer` cmdlet adds the local computer or remote computers to a domain or workgroup, or moves them from one domain to another.' - $mamlModelObject.Notes.Text.Substring(0,33) | Should be "- In Windows PowerShell 2.0, the " - } - - It 'Validates the examples by checking Add-Computer Example 1' { - - $mamlModelObject.Examples[0].Title | Should be "Example 1: Add a local computer to a domain then restart the computer" - $mamlModelObject.Examples[0].Code[0].Text | Should be "Add-Computer -DomainName Domain01 -Restart" - $mamlModelObject.Examples[0].Remarks.Substring(0,120) | Should be "This command adds the local computer to the Domain01 domain and then restarts the computer to make the change effective." - - } - - It 'Validates Parameters by checking Add-Computer Computer Name and Local Credential in Domain ParameterSet'{ - - $Parameter = $mamlModelObject.Syntax[0].Parameters | Where-Object { $_.Name -eq "ComputerName" } - $Parameter.Name | Should be "ComputerName" - $Parameter.Type | Should be "string[]" - $Parameter.Required | Should be $false - } - - It 'Validates there is only 1 default parameterset and that it is the domain parameterset for Add-Computer'{ - - $DefaultParameterSet = $mamlModelObject.Syntax | Where-Object {$_.IsDefault} - $count = 0 - foreach($set in $DefaultParameterSet) - { - $count = $count +1 - } - $count | Should be 1 - - $DefaultParameterSetName = $mamlModelObject.Syntax | Where-Object {$_.IsDefault} | Select-Object ParameterSetName - $DefaultParameterSetName.ParameterSetName | Should be "Domain" - } - } - - Context 'Add-Member' { - # call non-exported function in the module scope - $mamlModelObject = & (Get-Module platyPS) { GetMamlObject -Cmdlet "Add-Member" } - - It 'Fetch MemberSet set name' { - $MemberSet = $mamlModelObject.Syntax | Where-Object {$_.ParameterSetName -eq 'MemberSet'} - ($MemberSet | Measure-Object).Count | Should Be 1 - } - - It 'populates ParameterValueGroup for MemberType' { - $Parameters = $mamlModelObject.Syntax.Parameters | Where-Object { $_.Name -eq "MemberType" } - ($Parameters | Measure-Object).Count | Should Be 1 - $Parameters | ForEach-Object { - $_.Name | Should be "MemberType" - $_.ParameterValueGroup.Count | Should be 16 - } - } - } - } - -#endregion -######################################################### -#region Checking Cab and File Naming Cmdlets - - Describe 'New-ExternalHelpCab' { - $OutputPath = "$TestDrive\CabTesting" - - New-Item -ItemType Directory -Path (Join-Path $OutputPath "\Source\Xml\") -ErrorAction SilentlyContinue | Out-Null - New-Item -ItemType Directory -Path (Join-Path $OutputPath "\Source\ModuleMd\") -ErrorAction SilentlyContinue | Out-Null - New-Item -ItemType Directory -Path (Join-Path $OutputPath "\OutXml") -ErrorAction SilentlyContinue | Out-Null - New-Item -ItemType Directory -Path (Join-Path $OutputPath "\OutXml2") -ErrorAction SilentlyContinue | Out-Null - New-Item -ItemType File -Path (Join-Path $OutputPath "\Source\Xml\") -Name "HelpXml.xml" -force | Out-Null - New-Item -ItemType File -Path (Join-Path $OutputPath "\Source\Xml\") -Name "Module.resources.psd1" | Out-Null - New-Item -ItemType File -Path (Join-Path $OutputPath "\Source\ModuleMd\") -Name "Module.md" -ErrorAction SilentlyContinue | Out-Null - New-Item -ItemType File -Path $OutputPath -Name "PlatyPs_00000000-0000-0000-0000-000000000000_helpinfo.xml" -ErrorAction SilentlyContinue | Out-Null - Set-Content -Path (Join-Path $OutputPath "\Source\Xml\HelpXml.xml") -Value "<node><test>Adding test content to ensure cab builds correctly.</test></node>" | Out-Null - Set-Content -Path (Join-Path $OutputPath "\Source\ModuleMd\Module.md") -Value "---`r`nModule Name: PlatyPs`r`nModule Guid: 00000000-0000-0000-0000-000000000000`r`nDownload Help Link: Somesite.com`r`nHelp Version: 5.0.0.1`r`nLocale: en-US`r`n---" | Out-Null - - Context 'MakeCab.exe' { - - It 'Validates that MakeCab.exe & Expand.exe exists'{ - - (Get-Command MakeCab) -ne $null | Should Be $True - (Get-Command Expand) -ne $null | Should Be $True - - } - } - - Context 'New-ExternalHelpCab function, External Help & HelpInfo' { - - $CmdletContentFolder = (Join-Path $OutputPath "\Source\Xml\") - $ModuleMdPageFullPath = (Join-Path $OutputPath "\Source\ModuleMd\Module.md") - - It 'validates the output of Cab creation' { - - New-ExternalHelpCab -CabFilesFolder $CmdletContentFolder -OutputFolder $OutputPath -LandingPagePath $ModuleMdPageFullPath -WarningAction SilentlyContinue - $cab = (Get-ChildItem (Join-Path $OutputPath "PlatyPs_00000000-0000-0000-0000-000000000000_en-US_HelpContent.cab")).FullName - $cabExtract = (Join-Path (Split-Path $cab -Parent) "OutXml") - - $cabExtract = Join-Path $cabExtract "HelpXml.xml" - - expand $cab /f:* $cabExtract - - (Get-ChildItem -Filter "*.cab" -Path "$OutputPath").Name | Should BeExactly "PlatyPs_00000000-0000-0000-0000-000000000000_en-US_HelpContent.cab" - (Get-ChildItem -Filter "*.xml" -Path "$OutputPath").Name | Should Be "PlatyPs_00000000-0000-0000-0000-000000000000_helpinfo.xml" - (Get-ChildItem -Filter "*.xml" -Path "$OutputPath\OutXml").Name | Should Be "HelpXml.xml" - (Get-ChildItem -Filter "*.zip" -Path "$OutputPath").Name | Should BeExactly "PlatyPs_00000000-0000-0000-0000-000000000000_en-US_HelpContent.zip" - Get-ChildItem -Filter "*.psd1" -Path "$OutputPath\OutXml" | Should BeNullOrEmpty - } - - It 'Creates a help info file'{ - [xml] $PlatyPSHelpInfo = Get-Content (Join-Path $OutputPath "PlatyPs_00000000-0000-0000-0000-000000000000_helpinfo.xml") - - $PlatyPSHelpInfo | Should Not Be $null - $PlatyPSHelpInfo.HelpInfo.SupportedUICultures.UICulture.UICultureName | Should Be "en-US" - $PlatyPSHelpInfo.HelpInfo.SupportedUICultures.UICulture.UICultureVersion | Should Be "5.0.0.1" - } - - It 'validates the version is incremented when the switch is used' { - New-ExternalHelpCab -CabFilesFolder $CmdletContentFolder -OutputFolder $OutputPath -LandingPagePath $ModuleMdPageFullPath -IncrementHelpVersion -WarningAction SilentlyContinue - [xml] $PlatyPSHelpInfo = Get-Content (Join-Path $OutputPath "PlatyPs_00000000-0000-0000-0000-000000000000_helpinfo.xml") - $PlatyPSHelpInfo | Should Not Be $null - $PlatyPSHelpInfo.HelpInfo.SupportedUICultures.UICulture.UICultureName | Should Be "en-US" - $PlatyPSHelpInfo.HelpInfo.SupportedUICultures.UICulture.UICultureVersion | Should Be "5.0.0.2" - } - - It 'Adds another help locale'{ - - Set-Content -Path (Join-Path $OutputPath "\Source\ModuleMd\Module.md") -Value "---`r`nModule Name: PlatyPs`r`nModule Guid: 00000000-0000-0000-0000-000000000000`r`nDownload Help Link: Somesite.com`r`nHelp Version: 5.0.0.1`r`nLocale: en-US`r`nAdditional Locale: fr-FR,ja-JP`r`nfr-FR Version: 1.2.3.4`r`nja-JP Version: 2.3.4.5`r`n---" | Out-Null - New-ExternalHelpCab -CabFilesFolder $CmdletContentFolder -OutputFolder $OutputPath -LandingPagePath $ModuleMdPageFullPath -WarningAction SilentlyContinue - [xml] $PlatyPSHelpInfo = Get-Content (Join-Path $OutputPath "PlatyPs_00000000-0000-0000-0000-000000000000_helpinfo.xml") - $Count = 0 - $PlatyPSHelpInfo.HelpInfo.SupportedUICultures.UICulture | ForEach-Object {$Count++} - - $Count | Should Be 3 - } - } - } - -#endregion -} - -Describe 'Update-MarkdownHelp -LogPath' { - - It 'checks the log exists' { - $drop = "TestDrive:\MD\SingleCommand" - Remove-Item -rec $drop -ErrorAction SilentlyContinue - New-MarkdownHelp -Command Add-History -OutputFolder $drop | Out-Null - Update-MarkdownHelp -Path $drop -LogPath "$drop\platyPsLog.txt" - (Get-Childitem $drop\platyPsLog.txt).Name | Should Be 'platyPsLog.txt' - } -} - - -Describe 'Get-MarkdownMetadata' { - Context 'Simple markdown file' { - Set-Content -Path TestDrive:\foo.md -Value @' - ---- -a : 1 - -b: 2 -foo: bar ---- - -this text would be ignored -'@ - It 'can parse out yaml snippet' { - $d = Get-MarkdownMetadata TestDrive:\foo.md - $d.Count | Should Be 3 - $d['a'] = '1' - $d['b'] = '2' - $d['foo'] = 'bar' - } - } -} - -Describe 'Update-MarkdownHelp with New-MarkdownHelp inlined functionality' { - $OutputFolder = 'TestDrive:\update-new' - - $originalFiles = New-MarkdownHelp -Module platyPS -OutputFolder $OutputFolder -WithModulePage - - It 'creates markdown in the first place' { - $originalFiles | Should Not Be $null - $originalFiles | Select-Object -First 2 | Remove-Item - } - - It 'updates markdown and creates removed files again' { - $updatedFiles = Update-MarkdownHelpModule -Path $OutputFolder - ($updatedFiles | Measure-Object).Count | Should Be (($originalFiles | Measure-Object).Count - 1) - } - - $OutputFolderDiff = 'TestDrive:\update-new\Test-RefreshModuleFunctionality.md' - - it 'remove platyPS.md and make sure its gone' { - $File = $originalFiles | Where { $_ -like '*platyPS.md' } - Remove-Item -Path $File -Confirm:$false - $FileList = Get-ChildItem -Path $OutputFolder | % { Write-Output $_.FullName } - ($FileList | Measure-Object).Count | Should Be (($originalFiles | Measure-Object).Count - 1) - } - - it 'update MarkdownHelpFile with -RefreshModulePage' { - $UpdatedFiles = Update-MarkdownHelpModule -Path $OutputFolder -RefreshModulePage - ($UpdatedFiles | Measure-Object).Count | Should Be (($originalFiles | Measure-Object).Count) - $UpdatedFiles | Where { $_ -like '*platyPS.md' } | Should -BeLike '*platyPS.md' - } - it 'update MarkdownHelpFile with -RefreshModulePage with parameter ModulePagePath' { - $UpdatedFiles = Update-MarkdownHelpModule -Path $OutputFolder -RefreshModulePage -ModulePagePath $OutputFolderDiff - ($UpdatedFiles | Measure-Object).Count | Should Be (($originalFiles | Measure-Object).Count) - $UpdatedFiles | Where { $_ -like '*platyPS.md' } | Should -Be $Null - $UpdatedFiles | Where { $_ -like '*Test-RefreshModuleFunctionality.md' } | Should -Not -Be $Null - } -} - -Describe 'Update-MarkdownHelp reflection scenario' { - - function normalizeEnds([string]$text) - { - $text -replace "`r`n?|`n", "`r`n" - } - - $OutputFolder = 'TestDrive:\CoolStuff' - - # bootstraping docs from some code - function global:Get-MyCoolStuff - { - param( - [string]$Foo - ) - } - - $v1md = New-MarkdownHelp -command Get-MyCoolStuff -OutputFolder $OutputFolder - - It 'produces original stub' { - $v1md.Name | Should Be 'Get-MyCoolStuff.md' - } - - It 'produce a dummy example' { - $v1md.FullName | Should FileContentMatch '### Example 1' - } - - $v1markdown = $v1md | Get-Content -Raw - - $newFooDescription = normalizeEnds @' -ThisIsFooDescription - -It has mutlilines. -And [hyper](http://link.com). - -- And a list. Yeap. -- Good stuff? -'@ - - It 'can update stub' { - $v15markdown = $v1markdown -replace ($LocalizedData.ParameterDescription -f 'Foo'), $newFooDescription - $v15markdown | Should BeLike "*ThisIsFooDescription*" - Set-Content -Encoding UTF8 -Path $v1md -Value $v15markdown - } - - # change definition of the function with additional parameter - function global:Get-MyCoolStuff - { - param( - [string]$Foo, - [string]$Bar - ) - } - - $v2md = Update-MarkdownHelp $v1md -Verbose -AlphabeticParamsOrder - - It 'upgrades stub' { - $v2md.Name | Should Be 'Get-MyCoolStuff.md' - } - - $v2maml = New-ExternalHelp -Path $v2md.FullName -OutputPath "$OutputFolder\v2" - $v2markdown = $v2md | Get-Content -raw - $help = Get-HelpPreview -Path $v2maml - - It 'has both parameters' { - $names = $help.Parameters.parameter.Name - ($names | Measure-Object).Count | Should Be 2 - $names[0] | Should Be 'Bar' - $names[1] | Should Be 'Foo' - } - - It 'preserves hyperlinks' { - $v2markdown.Contains($newFooDescription) | Should Be $true - } - - It 'has updated description for Foo' { - $fooParam = $help.Parameters.parameter | Where-Object {$_.Name -eq 'Foo'} - normalizeEnds($fooParam.Description.Text | Out-String) | Should Be (normalizeEnds @' -ThisIsFooDescription - -It has mutlilines. And hyper (http://link.com). - -- And a list. Yeap. - -- Good stuff? - -'@) - } - - It 'has a placeholder for example' { - ($Help.examples.example | Measure-Object).Count | Should Be 1 - $e = $Help.examples.example - $e.Title | Should Match '-+ Example 1 -+' - $e.Code | Should Match 'PS C:\>*' - } - - It 'Confirms that Update-MarkdownHelp correctly populates the Default Parameterset' -Skip:$global:IsUnix { - $outputOriginal = "TestDrive:\MarkDownOriginal" - $outputUpdated = "TestDrive:\MarkDownUpdated" - New-Item -ItemType Directory -Path $outputOriginal - New-Item -ItemType Directory -Path $outputUpdated - New-MarkdownHelp -Command "Add-Computer" -OutputFolder $outputOriginal -Force - Copy-Item -Path (Join-Path $outputOriginal Add-Computer.md) -Destination (Join-Path $outputUpdated Add-Computer.md) - Update-MarkdownHelp -Path $outputFolder - (Get-Content (Join-Path $outputOriginal Add-Computer.md)) | Should Be (Get-Content (Join-Path $outputUpdated Add-Computer.md)) - } - - It 'parameter type should not be fullname' { - $expectedParameters = normalizeEnds @' -Type: String -Type: String - -'@ - $expectedSyntax = normalizeEnds @' -Get-MyCoolStuff [[-Foo] <String>] [[-Bar] <String>] [<CommonParameters>] - -'@ - normalizeEnds($v2md | Get-Content | Where-Object {$_.StartsWith('Type: ')} | Out-String) | Should Be $expectedParameters - normalizeEnds($v2md | Get-Content | Where-Object {$_.StartsWith('Get-MyCoolStuff')} | Out-String) | Should Be $expectedSyntax - } - - $v3md = Update-MarkdownHelp $v2md -Verbose -AlphabeticParamsOrder -UseFullTypeName - - $v3markdown = $v3md | Get-Content - - It 'parameter type should be fullname' { - $expectedParameters = normalizeEnds @' -Type: System.String -Type: System.String - -'@ - $expectedSyntax = normalizeEnds @' -Get-MyCoolStuff [[-Foo] <String>] [[-Bar] <String>] [<CommonParameters>] - -'@ - normalizeEnds($v3markdown | Where-Object {$_.StartsWith('Type: ')} | Out-String) | Should Be $expectedParameters - normalizeEnds($v3markdown | Where-Object {$_.StartsWith('Get-MyCoolStuff')} | Out-String) | Should Be $expectedSyntax - } - - It 'all the other part should be the same except line with parameters' { - $expectedContent = $v2md | Get-Content | Select-String -pattern "Type: |Get-MyCoolStuff" -notmatch | Out-String - $v3markdown | Select-String -pattern "Type: |Get-MyCoolStuff" -notmatch | Out-String | Should Be $expectedContent - - } -} - -Describe 'Update Markdown Help' { - - $output = "TestDrive:\" - - $ValidHelpFileName = "Microsoft.PowerShell.Archive-help.xml" - $md = @' ---- -external help file: ABadFileName-Help.xml -online version: http://go.microsoft.com/fwlink/?LinkId=821655 -schema: 2.0.0 ---- - -# Expand-Archive -## SYNOPSIS -Extracts files from a specified archive (zipped) file. - -## SYNTAX - -### Path (Default) -``` -Expand-Archive [-Path] <String> [[-DestinationPath] <String>] [-Force] [-WhatIf] [-Confirm] - [<CommonParameters>] -``` - -### LiteralPath -``` -Expand-Archive -LiteralPath <String> [[-DestinationPath] <String>] [-Force] [-WhatIf] [-Confirm] - [<CommonParameters>] -``` - -## DESCRIPTION -The Expand-Archive cmdlet extracts files from a specified zipped archive file to a specified destination folder. -An archive file allows multiple files to be packaged, and optionally compressed, into a single zipped file for easier distribution and storage. - -## EXAMPLES - -### Example 1: Extract the contents of an archive -``` -PS C:\>Expand-Archive -LiteralPath C:\Archives\Draft.Zip -DestinationPath C:\Reference -``` - -This command extracts the contents of an existing archive file, Draft.zip, into the folder specified by the DestinationPath parameter, C:\Reference. - -### Example 2: Extract the contents of an archive in the current folder -``` -PS C:\>Expand-Archive -Path Draft.Zip -DestinationPath C:\Reference -``` - -This command extracts the contents of an existing archive file in the current folder, Draft.zip, into the folder specified by the DestinationPath parameter, C:\Reference. - -## PARAMETERS - -### -DestinationPath -Specifies the path to the folder in which you want the command to save extracted files. -Enter the path to a folder, but do not specify a file name or file name extension. -This parameter is required. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 2 -Default value: -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Force -Forces the command to run without asking for user confirmation. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -LiteralPath -Specifies the path to an archive file. -Unlike the Path parameter, the value of LiteralPath is used exactly as it is typed. -Wildcard characters are not supported. -If the path includes escape characters, enclose each escape character in single quotation marks, to instruct Windows PowerShell not to interpret any characters as escape sequences. - -```yaml -Type: String -Parameter Sets: LiteralPath -Aliases: PSPath - -Required: True -Position: Named -Default value: -Accept pipeline input: True (ByPropertyName) -Accept wildcard characters: False -``` - -### -Path -Specifies the path to the archive file. - -```yaml -Type: String -Parameter Sets: Path -Aliases: - -Required: True -Position: 1 -Default value: -Accept pipeline input: True (ByPropertyName, ByValue) -Accept wildcard characters: False -``` - -### -Confirm -Prompts you for confirmation before running the cmdlet.Prompts you for confirmation before running the cmdlet. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: cf - -Required: False -Position: Named -Default value: False -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -WhatIf -Shows what would happen if the cmdlet runs. -The cmdlet is not run.Shows what would happen if the cmdlet runs. -The cmdlet is not run. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: wi - -Required: False -Position: Named -Default value: False -Accept pipeline input: False -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### System.String -You can pipe a string that contains a path to an existing archive file. - -## OUTPUTS - -### System.IO.FileInfo or System.IO.DirectoryInfo - -## NOTES - -## RELATED LINKS - -[Compress-Archive]() -'@ - - Set-Content -Path "$outFolder\Expand-Archive.md" -Value $md - Update-MarkdownHelp -Path "$outFolder\Expand-Archive.md" - $updatedMd = Get-Content "$outFolder\Expand-Archive.md" - - It 'Verifies that a bad metadata value for the help file is fixed on update' { - $MetaData = Get-MarkdownMetadata -Markdown ($updatedMd | Out-String) - $MetaData["external help file"] | Should Be $ValidHelpFileName - } - - @('## ', '### ') | ForEach-Object { - It "use a single spacing for $_ sections" { - $lineStart = $_ - for ($i=2; $i -lt $updatedMd.Count; $i++) - { - if ($updatedMd[$i].StartsWith($lineStart)) - { - $updatedMd[$i - 1] | Should Be '' - $updatedMd[$i - 2] | Should Not Be '' - } - } - } - } -} - -Describe 'Create About Topic Markdown and Txt' { - - $output = "TestDrive:\" - $aboutTopicName = "PlatyPS" - $templateLocation = (Split-Path ((Get-Module $aboutTopicName).Path) -Parent) + "\templates\aboutTemplate.md" - $AboutTopicsOutputFolder = Join-Path $output "About" - New-Item -Path $AboutTopicsOutputFolder -ItemType Directory - - - It 'Checks the about topic is created with proper file name, and the content is correctly written' { - - $aboutContent = Get-Content $templateLocation - $aboutContent = $aboutContent.Replace("{{FileNameForHelpSystem}}",("about_" + $aboutTopicName)) - $aboutContent = $aboutContent.Replace("{{TOPIC NAME}}",$aboutTopicName) - - New-MarkdownAboutHelp -OutputFolder $output -AboutName $aboutTopicName - - Test-Path (Join-Path $output ("about_$($aboutTopicName).md")) | Should Be $true - Get-Content (Join-Path $output ("about_$($aboutTopicName).md")) | Should Be $aboutContent - } - - It 'Checks the about topic is created with proper file name, and the content is correctly written - avoiding doubled about' { - - $aboutTopicName = "PlatyPS_about_doubled" - - $aboutContent = Get-Content $templateLocation - $aboutContent = $aboutContent.Replace("{{FileNameForHelpSystem}}",("about_" + $aboutTopicName)) - $aboutContent = $aboutContent.Replace("{{TOPIC NAME}}",$aboutTopicName) - - New-MarkdownAboutHelp -OutputFolder $output -AboutName $("about_" + $aboutTopicName) - - Test-Path (Join-Path $output ("about_$($aboutTopicName).md")) | Should Be $true - Get-Content (Join-Path $output ("about_$($aboutTopicName).md")) | Should Be $aboutContent - } - - It 'Can generate external help for a directly-specified "about" markdown file' { - - New-MarkdownAboutHelp -OutputFolder $output -AboutName 'JustOne' - - $aboutMdPath = Join-Path $output "about_JustOne.md" - - New-ExternalHelp -Path $aboutMdPath -OutputPath $AboutTopicsOutputFolder - - $aboutExternalHelpPath = Join-Path $AboutTopicsOutputFolder 'about_JustOne.help.txt' - - Test-Path $aboutExternalHelpPath | Should Be $true - } - - It 'Can generate external help for a directly-specified "about" markdown file - avoiding doubled about_' { - - New-MarkdownAboutHelp -OutputFolder $output -AboutName 'about_JustSecond' - - $aboutMdPath = Join-Path $output "about_JustSecond.md" - - New-ExternalHelp -Path $aboutMdPath -OutputPath $AboutTopicsOutputFolder - - $aboutExternalHelpPath = Join-Path $AboutTopicsOutputFolder 'about_JustSecond.help.txt' - - Test-Path $aboutExternalHelpPath | Should Be $true - } - - It 'Takes constructed markdown about topics and converts them to text with proper character width'{ - - New-MarkdownAboutHelp -OutputFolder $AboutTopicsOutputFolder -AboutName "AboutTopic" - - New-ExternalHelp -Path $AboutTopicsOutputFolder -OutputPath $AboutTopicsOutputFolder - - $lineWidthCheck = $true; - - $AboutTxtFilePath = Join-Path $AboutTopicsOutputFolder "about_AboutTopic.help.txt" - - $AboutContent = Get-Content $AboutTxtFilePath - - $AboutContent | ForEach-Object { - if($_.Length -gt 80) - { - $lineWidthCheck = $false - } - } - - (Get-ChildItem $AboutTxtFilePath | Measure-Object).Count | Should Be 1 - $lineWidthCheck | Should Be $true - } - - It 'Adds a yaml block to the AboutTopic and verifies build as expected'{ - - $content = Get-Content (Join-Path $output ("about_$($aboutTopicName).md")) - $content = ("---Yaml: Stuff---" + $content) - Set-Content -Value $content -Path (Join-Path $output ("about_$($aboutTopicName).md")) -Force - - Test-Path (Join-Path $output ("about_$($aboutTopicName).md")) | Should Be $true - Get-Content (Join-Path $output ("about_$($aboutTopicName).md")) | Should Be $content - } -} - -Describe 'Merge-MarkdownHelp' { - - Context 'single file, ignore examples' { - function global:Test-PlatyPSMergeFunction - { - param( - [string]$First - ) - } - - $file1 = New-MarkdownHelp -Command Test-PlatyPSMergeFunction -OutputFolder TestDrive:\mergeFile1 -Force - $maml1 = $file1 | New-ExternalHelp -OutputPath TestDrive:\1.xml -Force - $help1 = Get-HelpPreview -Path $maml1 - $help1.examples = @() - - function global:Test-PlatyPSMergeFunction - { - param( - [string]$Second - ) - } - - $file2 = New-MarkdownHelp -Command Test-PlatyPSMergeFunction -OutputFolder TestDrive:\mergeFile2 -Force - $maml2 = $file2 | New-ExternalHelp -OutputPath TestDrive:\2.xml -Force - $help2 = Get-HelpPreview -Path $maml2 - $help2.examples = @() - - It 'generates merged markdown with applicable tags' { - $fileNew = Merge-MarkdownHelp -Path @($file1, $file2) -OutputPath TestDrive:\mergeFileOut -Force - - $mamlNew1 = $fileNew | New-ExternalHelp -OutputPath TestDrive:\1new.xml -Force -ApplicableTag('mergeFile1') - $helpNew1 = Get-HelpPreview -Path $mamlNew1 - $helpNew1.examples = @() - - $mamlNew2 = $fileNew | New-ExternalHelp -OutputPath TestDrive:\2new.xml -Force -ApplicableTag('mergeFile2') - $helpNew2 = Get-HelpPreview -Path $mamlNew2 - $helpNew2.examples = @() - - ($helpNew1 | Out-String) | Should Be ($help1 | Out-String) - ($helpNew2 | Out-String) | Should Be ($help2 | Out-String) - } - } - - Context 'two file' { - function global:Test-PlatyPSMergeFunction1() {} - function global:Test-PlatyPSMergeFunction2() {} - - $files = @() - $files += New-MarkdownHelp -Command Test-PlatyPSMergeFunction1 -OutputFolder TestDrive:\mergePath1 -Force - $files += New-MarkdownHelp -Command Test-PlatyPSMergeFunction1, Test-PlatyPSMergeFunction2 -OutputFolder TestDrive:\mergePath2 -Force - - It 'generates merged markdown with applicable tags' { - $fileNew = Merge-MarkdownHelp -Path $files -OutputPath TestDrive:\mergePathOut -Force - - $mamlNew1 = $fileNew | New-ExternalHelp -OutputPath TestDrive:\1new.xml -Force -ApplicableTag('mergePath1') - $helpNew1 = Get-HelpPreview -Path $mamlNew1 - - $mamlNew2 = $fileNew | New-ExternalHelp -OutputPath TestDrive:\2new.xml -Force -ApplicableTag('mergePath2') - $helpNew2 = Get-HelpPreview -Path $mamlNew2 - - $names1 = $helpNew1.Name - $names2 = $helpNew2.Name - - ($names1 | measure).Count | Should Be 1 - $names1 | Should Be 'Test-PlatyPSMergeFunction1' - - ($names2 | measure).Count | Should Be 2 - $names2[0] | Should Be 'Test-PlatyPSMergeFunction1' - $names2[1] | Should Be 'Test-PlatyPSMergeFunction2' - } - } -} - -Describe 'New-YamlHelp' { - - New-YamlHelp "$root\docs\New-YamlHelp.md" -OutputFolder "$outFolder\yaml" -Force - - $yamlContent = Get-Content "$outFolder\yaml\New-YamlHelp.yml" -Raw - - $deserializer = (New-Object -TypeName 'YamlDotNet.Serialization.DeserializerBuilder').WithNamingConvention((New-Object -TypeName 'YamlDotNet.Serialization.NamingConventions.CamelCaseNamingConvention')).Build() - - $yamlModel = $deserializer.Deserialize($yamlContent, [type]"Markdown.MAML.Model.YAML.YamlCommand") - - It 'serializes key properties correctly' { - $yamlModel.Name | Should Be 'New-YamlHelp' - $yamlModel.Module.Name | Should Be 'platyPS' - - $yamlModel.RequiredParameters.Count | Should Be 2 - - $yamlModel.RequiredParameters[0].Name | Should Be 'Path' - $yamlModel.RequiredParameters[1].Name | Should Be 'OutputFolder' - - $yamlModel.OptionalParameters.Count | Should Be 2 - - $yamlModel.OptionalParameters[0].Name | Should Be 'Encoding' - $yamlModel.OptionalParameters[1].Name | Should Be 'Force' - } - - It 'throws for OutputFolder that is a file'{ - { New-YamlHelp "$root\docs\New-YamlHelp.md" -OutputFolder "$outFolder\yaml\New-YamlHelp.yml" } | Should Throw - } -} diff --git a/v2docs/Microsoft.PowerShell.PlatyPS/Compare-CommandHelp.md b/v2docs/Microsoft.PowerShell.PlatyPS/Compare-CommandHelp.md deleted file mode 100644 index 49409575..00000000 --- a/v2docs/Microsoft.PowerShell.PlatyPS/Compare-CommandHelp.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -document type: cmdlet -external help file: Microsoft.PowerShell.PlatyPS.dll-Help.xml -HelpUri: '' -Locale: en-US -Module Name: Microsoft.PowerShell.PlatyPS -ms.custom: OPS12 -ms.date: 10/14/2024 -PlatyPS schema version: 2024-05-01 -title: Compare-CommandHelp ---- - -# Compare-CommandHelp - -## SYNOPSIS - -Compares two **CommandHelp** objects and produces a detailed report showing the differences. - -## SYNTAX - -### __AllParameterSets - -``` -Compare-CommandHelp [-ReferenceCommandHelp] <CommandHelp> [-DifferenceCommandHelp] <CommandHelp> - [-PropertyNamesToExclude <string[]>] [<CommonParameters>] -``` - -## ALIASES - -## DESCRIPTION - -`Compare-CommandHelp` is a troubleshooting tool that compares two CommandHelp objects and produces a -detailed report showing the differences. For example, you can use this to compare objects imported -from different sources, such as two different versions of Markdown files. - -## EXAMPLES - -### Example 1 - -```powershell -$refcmd = Import-MarkdownCommandHelp -Path .\v1\Microsoft.PowerShell.PlatyPS\Compare-CommandHelp.md -$diffcmd = Import-MarkdownCommandHelp -Path .\v2\Microsoft.PowerShell.PlatyPS\Compare-CommandHelp.md -Compare-CommandHelp -ReferenceCommandHelp $refcmd -DifferenceCommandHelp $diffcmd > .\diff.log -``` - -## PARAMETERS - -### -DifferenceCommandHelp - -The CommandHelp object to compare against the reference object. - -```yaml -Type: Microsoft.PowerShell.PlatyPS.Model.CommandHelp -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: 1 - IsRequired: true - ValueFromPipeline: false - ValueFromPipelineByPropertyName: true - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -PropertyNamesToExclude - -A list of one or more property names to exclude from the comparison. - -```yaml -Type: System.String[] -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -ReferenceCommandHelp - -The base CommandHelp object to be compared to the difference object. - -```yaml -Type: Microsoft.PowerShell.PlatyPS.Model.CommandHelp -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: 0 - IsRequired: true - ValueFromPipeline: false - ValueFromPipelineByPropertyName: true - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### CommonParameters - -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, --InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, --ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see -[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### Microsoft.PowerShell.PlatyPS.Model.CommandHelp - -## OUTPUTS - -### System.String - -## NOTES - -## RELATED LINKS - -- [Import-MarkdownHelp](Import-MarkdownHelp.md) -- [Import-YamlCommandHelp](Import-YamlCommandHelp.md) diff --git a/v2docs/Microsoft.PowerShell.PlatyPS/Export-MamlCommandHelp.md b/v2docs/Microsoft.PowerShell.PlatyPS/Export-MamlCommandHelp.md deleted file mode 100644 index e3bb41de..00000000 --- a/v2docs/Microsoft.PowerShell.PlatyPS/Export-MamlCommandHelp.md +++ /dev/null @@ -1,210 +0,0 @@ ---- -document type: cmdlet -external help file: Microsoft.PowerShell.PlatyPS.dll-Help.xml -HelpUri: '' -Locale: en-US -Module Name: Microsoft.PowerShell.PlatyPS -ms.custom: OPS12 -ms.date: 10/14/2024 -PlatyPS schema version: 2024-05-01 -title: Export-MamlCommandHelp ---- - -# Export-MamlCommandHelp - -## SYNOPSIS - -Exports **CommandHelp** objects to a MAML file. - -## SYNTAX - -### __AllParameterSets - -``` -Export-MamlCommandHelp [-CommandHelp] <CommandHelp[]> [-OutputFolder] <string> - [-Encoding <Encoding>] [-Force] [-WhatIf] [-Confirm] [<CommonParameters>] -``` - -## ALIASES - -## DESCRIPTION - -This command converts **CommandHelp** objects to a MAML file. The MAML file contains help content in -the format used by the `Get-Help` command. - -## EXAMPLES - -### Example 1 - Create the MAML help file for a module - -```powershell -$mdfiles = Measure-PlatyPSMarkdown -Path .\v2\Microsoft.PowerShell.PlatyPS\*.md -$mdfiles | Where-Object Filetype -match 'CommandHelp' | - Import-MarkdownCommandHelp -Path {$_.FilePath} | - Export-MamlCommandHelp -OutputFolder .\maml -``` - -```Output - Directory: D:\Git\PS-Src\platyPS\v2docs\maml - -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a--- 8/26/2024 3:18 PM 160928 Microsoft.PowerShell.PlatyPS-Help.xml -``` - -## PARAMETERS - -### -CommandHelp - -One or more **CommandHelp** objects to export. - -```yaml -Type: Microsoft.PowerShell.PlatyPS.Model.CommandHelp[] -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: 0 - IsRequired: true - ValueFromPipeline: true - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Confirm - -Prompts you for confirmation before running the cmdlet. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: -- cf -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Encoding - -The encoding to use when writing the markdown file. If no value is specified, encoding defaults to -the value of the `$OutputEncoding` preference variable. - -```yaml -Type: System.Text.Encoding -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Force - -Use the **Force** parameter to overwrite the output file if it already exists. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -OutputFolder - -The folder where the markdown file is saved. If the folder doesn't exist, it's created. - -```yaml -Type: System.String -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: 1 - IsRequired: true - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -WhatIf - -Shows what would happen if the cmdlet runs. The cmdlet isn't run. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: -- wi -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### CommonParameters - -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, --InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, --ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see -[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### Microsoft.PowerShell.PlatyPS.Model.CommandHelp - -## OUTPUTS - -### System.IO.FileInfo - -## NOTES - -## RELATED LINKS - -- [Import-MarkdownCommandHelp](Import-MarkdownCommandHelp.md) diff --git a/v2docs/Microsoft.PowerShell.PlatyPS/Export-MarkdownCommandHelp.md b/v2docs/Microsoft.PowerShell.PlatyPS/Export-MarkdownCommandHelp.md deleted file mode 100644 index 15ccc084..00000000 --- a/v2docs/Microsoft.PowerShell.PlatyPS/Export-MarkdownCommandHelp.md +++ /dev/null @@ -1,279 +0,0 @@ ---- -document type: cmdlet -external help file: Microsoft.PowerShell.PlatyPS.dll-Help.xml -HelpUri: '' -Locale: en-US -Module Name: Microsoft.PowerShell.PlatyPS -ms.custom: OPS12 -ms.date: 10/14/2024 -PlatyPS schema version: 2024-05-01 -title: Export-MarkdownCommandHelp ---- - -# Export-MarkdownCommandHelp - -## SYNOPSIS - -Exports a **CommandHelp** object to a markdown file. - -## SYNTAX - -### __AllParameterSets - -``` -Export-MarkdownCommandHelp [-CommandHelp] <CommandHelp[]> [-Encoding <Encoding>] [-Force] - [-OutputFolder <string>] [-Metadata <hashtable>] [-WhatIf] [-Confirm] [<CommonParameters>] -``` - -## ALIASES - -## DESCRIPTION - -This command exports a **CommandHelp** object to a markdown file. You can add metadata frontmatter -to the markdown file by using the **Metadata** parameter. You can get a **CommandHelp** object by -using the `Export-MarkdownCommandHelp` cmdlet or one of the `Import-*` cmdlets. - -## EXAMPLES - -### Example 1 - Convert old Markdown help content to the new format - -This example imports Markdown help in the old format from the `.\v1` folder and exports it to the -`.\v2` folder in the new format. - -```powershell -$chobj = Import-MarkdownCommandHelp -Path .\v1\Export-YamlModuleFile.md -Export-MarkdownCommandHelp -CommandHelp $chobj -OutputFolder .\v2 -``` - -```Output - Directory: D:\Git\PS-Src\platyPS\v2docs\v2 - -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a--- 5/20/2024 3:33 PM 2892 Export-YamlModuleFile.md -``` - -### Example 2 - Convert a folder of old Markdown help content to the new format - -This example imports Markdown help in the old format from the `.\v1` folder and exports it to the -`.\v1\new` folder in the new format. If necessary, `Export-MarkdownCommandHelp` creates the -destination folders. The new markdown files are written to folder named for the module they belong -to. - -```powershell -$mdfiles = Measure-PlatyPSMarkdown -Path .\v1\Microsoft.PowerShell.PlatyPS\*.md -$mdfiles | Where-Object Filetype -match 'CommandHelp' | - Import-MarkdownCommandHelp -Path {$_.FilePath} | - Export-MarkdownCommandHelp -OutputFolder .\v1\new -``` - -```Output - Directory: D:\Git\PS-Src\platyPS\v2docs\v1\new\Microsoft.PowerShell.PlatyPS - -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a--- 8/26/2024 3:30 PM 3194 Compare-CommandHelp.md --a--- 8/26/2024 3:30 PM 4282 Export-MamlCommandHelp.md --a--- 8/26/2024 3:30 PM 6401 Export-MarkdownCommandHelp.md --a--- 8/26/2024 3:30 PM 4874 Export-MarkdownModuleFile.md --a--- 8/26/2024 3:30 PM 6429 Export-YamlCommandHelp.md --a--- 8/26/2024 3:30 PM 5601 Export-YamlModuleFile.md --a--- 8/26/2024 3:30 PM 2724 Import-MamlHelp.md --a--- 8/26/2024 3:30 PM 3733 Import-MarkdownCommandHelp.md --a--- 8/26/2024 3:30 PM 3870 Import-MarkdownModuleFile.md --a--- 8/26/2024 3:30 PM 3907 Import-YamlCommandHelp.md --a--- 8/26/2024 3:30 PM 3477 Import-YamlModuleFile.md --a--- 8/26/2024 3:30 PM 2088 Measure-PlatyPSMarkdown.md --a--- 8/26/2024 3:30 PM 4748 New-CommandHelp.md --a--- 8/26/2024 3:30 PM 8647 New-MarkdownCommandHelp.md --a--- 8/26/2024 3:30 PM 5086 New-MarkdownModuleFile.md --a--- 8/26/2024 3:30 PM 3080 Test-MarkdownCommandHelp.md --a--- 8/26/2024 3:30 PM 3041 Update-CommandHelp.md --a--- 8/26/2024 3:30 PM 3981 Update-MarkdownCommandHelp.md --a--- 8/26/2024 3:30 PM 5548 Update-MarkdownModuleFile.md -``` - -## PARAMETERS - -### -CommandHelp - -The **CommandHelp** object to export. You can pass the **CommandHelp** object on the pipeline or by -using the **Command** parameter. - -```yaml -Type: Microsoft.PowerShell.PlatyPS.Model.CommandHelp[] -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: 0 - IsRequired: true - ValueFromPipeline: true - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Confirm - -Prompts you for confirmation before running the cmdlet. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: -- cf -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Encoding - -The encoding to use when writing the markdown file. If no value is specified, encoding defaults to -the value of the `$OutputEncoding` preference variable. - -```yaml -Type: System.Text.Encoding -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Force - -Use the **Force** parameter to overwrite the output file if it already exists. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Metadata - -The metadata to add to the frontmatter of the markdown file. The metadata is a hashtable where the -you specify the key and value pairs to add to the frontmatter. New key names are added to the -existing frontmatter. The values of existing keys are overwritten. - -```yaml -Type: System.Collections.Hashtable -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -OutputFolder - -The folder where the markdown file is saved. If the folder doesn't exist, it's created. - -```yaml -Type: System.String -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -WhatIf - -Shows what would happen if the cmdlet runs. The cmdlet is not run. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: -- wi -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### CommonParameters - -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, --InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, --ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see -[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### Microsoft.PowerShell.PlatyPS.Model.CommandHelp - -## OUTPUTS - -### System.IO.FileInfo - -## NOTES - -## RELATED LINKS - -- [Export-YamlCommandHelp](Export-YamlCommandHelp.md) -- [Import-MarkdownCommandHelp](Import-MarkdownCommandHelp.md) -- [Import-YamlCommandHelp](Import-YamlCommandHelp.md) diff --git a/v2docs/Microsoft.PowerShell.PlatyPS/Export-MarkdownModuleFile.md b/v2docs/Microsoft.PowerShell.PlatyPS/Export-MarkdownModuleFile.md deleted file mode 100644 index 06b48276..00000000 --- a/v2docs/Microsoft.PowerShell.PlatyPS/Export-MarkdownModuleFile.md +++ /dev/null @@ -1,239 +0,0 @@ ---- -document type: cmdlet -external help file: Microsoft.PowerShell.PlatyPS.dll-Help.xml -HelpUri: '' -Locale: en-US -Module Name: Microsoft.PowerShell.PlatyPS -ms.custom: OPS12 -ms.date: 10/14/2024 -PlatyPS schema version: 2024-05-01 -title: Export-MarkdownModuleFile ---- - -# Export-MarkdownModuleFile - -## SYNOPSIS - -Exports a **ModuleFileInfo** object to a markdown file. - -## SYNTAX - -### __AllParameterSets - -``` -Export-MarkdownModuleFile [-ModuleFileInfo] <ModuleFileInfo[]> [-Encoding <Encoding>] [-Force] - [-Metadata <hashtable>] [-OutputFolder <string>] [-WhatIf] [-Confirm] [<CommonParameters>] -``` - -## ALIASES - -## DESCRIPTION - -This command exports a **ModuleFileInfo** object to a markdown file. You can add metadata -frontmatter to the markdown file by using the **Metadata** parameter. You can get a -**ModuleFileInfo** object by using the `Import-MarkdownModuleFile` cmdlet. You can import a module -file that's written in the old format and export it to the new format. - -## EXAMPLES - -### Example 1 - Convert an old module file to the new format - -In this example, a **ModuleFileInfo** object by importing a module Markdown file from the `.\v1` -folder. That object is then exported to a Markdown file in the new format using the -`Export-MarkdownModuleFile`. - -```powershell -Import-MarkdownModuleFile -Path .\v1\Microsoft.PowerShell.PlatyPS\Microsoft.PowerShell.PlatyPS.md | - Export-MarkdownModuleFile -OutputFolder .\v1\new\Microsoft.PowerShell.PlatyPS -Force -``` - -```Output - Directory: D:\Git\PS-Src\platyPS\v2docs\v1\new\Microsoft.PowerShell.PlatyPS - -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a--- 8/26/2024 3:38 PM 2716 Microsoft.PowerShell.PlatyPS.md -``` - -## PARAMETERS - -### -Confirm - -Prompts you for confirmation before running the cmdlet. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: -- cf -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Encoding - -The encoding to use when writing the markdown file. If no value is specified, encoding defaults to -the value of the `$OutputEncoding` preference variable. - -```yaml -Type: System.Text.Encoding -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Force - -Use the **Force** parameter to overwrite the output file if it already exists. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Metadata - -The metadata to add to the frontmatter of the markdown file. The metadata is a hashtable where the -you specify the key and value pairs to add to the frontmatter. New key names are added to the -existing frontmatter. The values of existing keys are overwritten. - -```yaml -Type: System.Collections.Hashtable -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -ModuleFileInfo - -The **ModuleFileInfo** object to export to a markdown file. This object is created by the -`Import-MarkdownModuleFile` cmdlet. - -```yaml -Type: Microsoft.PowerShell.PlatyPS.ModuleFileInfo[] -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: 0 - IsRequired: true - ValueFromPipeline: true - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -OutputFolder - -The folder where the markdown file is saved. If the folder doesn't exist, it's created. - -```yaml -Type: System.String -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -WhatIf - -Shows what would happen if the cmdlet runs. The cmdlet isn't run. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: -- wi -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### CommonParameters - -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, --InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, --ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see -[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### Microsoft.PowerShell.PlatyPS.ModuleFileInfo - -## OUTPUTS - -### System.IO.FileInfo - -## NOTES - -## RELATED LINKS - -- [Import-MarkdownModuleFile](Import-MarkdownModuleFile.md) diff --git a/v2docs/Microsoft.PowerShell.PlatyPS/Export-YamlCommandHelp.md b/v2docs/Microsoft.PowerShell.PlatyPS/Export-YamlCommandHelp.md deleted file mode 100644 index 9193f7af..00000000 --- a/v2docs/Microsoft.PowerShell.PlatyPS/Export-YamlCommandHelp.md +++ /dev/null @@ -1,260 +0,0 @@ ---- -document type: cmdlet -external help file: Microsoft.PowerShell.PlatyPS.dll-Help.xml -HelpUri: '' -Locale: en-US -Module Name: Microsoft.PowerShell.PlatyPS -ms.custom: OPS12 -ms.date: 10/14/2024 -PlatyPS schema version: 2024-05-01 -title: Export-YamlCommandHelp ---- - -# Export-YamlCommandHelp - -## SYNOPSIS - -Exports **CommandHelp** objects to YAML files. - -## SYNTAX - -### __AllParameterSets - -``` -Export-YamlCommandHelp [-CommandHelp] <CommandHelp[]> [-Encoding <Encoding>] [-Force] - [-OutputFolder <string>] [-Metadata <hashtable>] [-WhatIf] [-Confirm] [<CommonParameters>] -``` - -## ALIASES - -## DESCRIPTION - -This command exports a **CommandHelp** object to a Yaml file. You can add metadata frontmatter -to the Yaml file by using the **Metadata** parameter. You can get a **CommandHelp** object by -using the `Export-YamlCommandHelp` cmdlet or one of the `Import-*` cmdlets. - -## EXAMPLES - -### Example 1 - Convert Markdown command help content to Yaml format - -This example imports Markdown help in the old format from the `.\v1` folder and exports it to the -`.\v2` folder in the new format. - -```powershell -$mdfiles = Measure-PlatyPSMarkdown -Path .\v2\Microsoft.PowerShell.PlatyPS\*.md -$mdfiles | Where-Object Filetype -match 'CommandHelp' | - Import-MarkdownCommandHelp -Path {$_.FilePath} | - Export-YamlCommandHelp -OutputFolder .\v2\yaml -``` - -```Output - Directory: D:\Git\PS-Src\platyPS\v2docs\v2\yaml - -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a--- 8/26/2024 3:56 PM 3535 Compare-CommandHelp.yml --a--- 8/26/2024 3:56 PM 4776 Export-MamlCommandHelp.yml --a--- 8/26/2024 3:56 PM 8150 Export-MarkdownCommandHelp.yml --a--- 8/26/2024 3:56 PM 4998 Export-MarkdownModuleFile.yml --a--- 8/26/2024 3:56 PM 6357 Export-YamlCommandHelp.yml --a--- 8/26/2024 3:56 PM 5396 Export-YamlModuleFile.yml --a--- 8/26/2024 3:56 PM 3019 Import-MamlHelp.yml --a--- 8/26/2024 3:56 PM 4235 Import-MarkdownCommandHelp.yml --a--- 8/26/2024 3:56 PM 4318 Import-MarkdownModuleFile.yml --a--- 8/26/2024 3:56 PM 4391 Import-YamlCommandHelp.yml --a--- 8/26/2024 3:56 PM 3862 Import-YamlModuleFile.yml --a--- 8/26/2024 3:56 PM 2325 Measure-PlatyPSMarkdown.yml --a--- 8/26/2024 3:56 PM 5190 New-CommandHelp.yml --a--- 8/26/2024 3:56 PM 8335 New-MarkdownCommandHelp.yml --a--- 8/26/2024 3:56 PM 4697 New-MarkdownModuleFile.yml --a--- 8/26/2024 3:56 PM 3468 Test-MarkdownCommandHelp.yml --a--- 8/26/2024 3:56 PM 3172 Update-CommandHelp.yml --a--- 8/26/2024 3:56 PM 3908 Update-MarkdownCommandHelp.yml --a--- 8/26/2024 3:56 PM 5217 Update-MarkdownModuleFile.yml -``` - -## PARAMETERS - -### -CommandHelp - -The **CommandHelp** object to export. You can pass the **CommandHelp** object on the pipeline or by -using the **Command** parameter. - -```yaml -Type: Microsoft.PowerShell.PlatyPS.Model.CommandHelp[] -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: 0 - IsRequired: true - ValueFromPipeline: true - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Confirm - -Prompts you for confirmation before running the cmdlet. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: -- cf -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Encoding - -The encoding to use when writing the markdown file. If no value is specified, encoding defaults to -the value of the `$OutputEncoding` preference variable. - -```yaml -Type: System.Text.Encoding -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Force - -Use the **Force** parameter to overwrite the output file if it already exists. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Metadata - -The metadata to add to the frontmatter of the markdown file. The metadata is a hashtable where the -you specify the key and value pairs to add to the frontmatter. New key names are added to the -existing frontmatter. The values of existing keys are overwritten. - -```yaml -Type: System.Collections.Hashtable -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -OutputFolder - -The folder where the markdown file is saved. If the folder doesn't exist, it's created. - -```yaml -Type: System.String -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -WhatIf - -Shows what would happen if the cmdlet runs. The cmdlet isn't run. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: -- wi -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### CommonParameters - -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, --InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, --ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see -[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### Microsoft.PowerShell.PlatyPS.Model.CommandHelp - -## OUTPUTS - -### System.IO.FileInfo - -## NOTES - -## RELATED LINKS - -- [Export-YamlCommandHelp](Export-YamlCommandHelp.md) -- [Export-MarkdownCommandHelp](Export-MarkdownCommandHelp.md) -- [Import-MarkdownCommandHelp](Import-MarkdownCommandHelp.md) -- [Import-YamlCommandHelp](Import-YamlCommandHelp.md) diff --git a/v2docs/Microsoft.PowerShell.PlatyPS/Export-YamlModuleFile.md b/v2docs/Microsoft.PowerShell.PlatyPS/Export-YamlModuleFile.md deleted file mode 100644 index 994335c9..00000000 --- a/v2docs/Microsoft.PowerShell.PlatyPS/Export-YamlModuleFile.md +++ /dev/null @@ -1,237 +0,0 @@ ---- -document type: cmdlet -external help file: Microsoft.PowerShell.PlatyPS.dll-Help.xml -HelpUri: '' -Locale: en-US -Module Name: Microsoft.PowerShell.PlatyPS -ms.custom: OPS12 -ms.date: 10/14/2024 -PlatyPS schema version: 2024-05-01 -title: Export-YamlModuleFile ---- - -# Export-YamlModuleFile - -## SYNOPSIS - -Exports a **ModuleFileInfo** object to a Yaml file. - -## SYNTAX - -### __AllParameterSets - -``` -Export-YamlModuleFile [-ModuleFileInfo] <ModuleFileInfo[]> [-Encoding <Encoding>] [-Force] - [-OutputFolder <string>] [-Metadata <hashtable>] [-WhatIf] [-Confirm] [<CommonParameters>] -``` - -## ALIASES - -## DESCRIPTION - -This command exports a **ModuleFileInfo** object to a markdown file. You can get a -**ModuleFileInfo** object by using the `Import-MarkdownModuleFile` cmdlet. You can import a module -file that's written in the old format and export it to the new format. - -## EXAMPLES - -### Example 1 - Export a ModuleFileInfo object to a markdown file - -In this example, a **ModuleFileInfo** object by importing a module Markdown file. That object is -then exported to a Yaml file using the `Export-YamlModuleFile`. - -```powershell -Import-MarkdownModuleFile -Path .\v2\Microsoft.PowerShell.PlatyPS\Microsoft.PowerShell.PlatyPS.md | - Export-YamlModuleFile -OutputFolder .\v2\yaml -``` - -```Output - Directory: D:\Git\PS-Src\platyPS\v2docs\v2\yaml - -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a--- 8/26/2024 4:00 PM 2594 Microsoft.PowerShell.PlatyPS.yml -``` - -## PARAMETERS - -### -Confirm - -Prompts you for confirmation before running the cmdlet. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: -- cf -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Encoding - -The encoding to use when writing the markdown file. If no value is specified, encoding defaults to -the value of the `$OutputEncoding` preference variable. - -```yaml -Type: System.Text.Encoding -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Force - -Use the **Force** parameter to overwrite the output file if it already exists. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Metadata - -The metadata to add to the markdown file. The metadata is a hashtable that contains key-value pairs. - -```yaml -Type: System.Collections.Hashtable -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -ModuleFileInfo - -The **ModuleFileInfo** object to export. You can pass the **ModuleFileInfo** object on the pipeline -or by using the **ModuleFileInfo** parameter. - -```yaml -Type: Microsoft.PowerShell.PlatyPS.ModuleFileInfo[] -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: 0 - IsRequired: true - ValueFromPipeline: true - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -OutputFolder - -The **ModuleFileInfo** object to export to a markdown file. This object is created by the -`Import-MarkdownModuleFile` cmdlet. - -```yaml -Type: System.String -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -WhatIf - -Shows what would happen if the cmdlet runs. The cmdlet isn't run. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: -- wi -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### CommonParameters - -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, --InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, --ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see -[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### Microsoft.PowerShell.PlatyPS.ModuleFileInfo - -## OUTPUTS - -### System.IO.FileInfo - -## NOTES - -## RELATED LINKS - -- [Export-MarkdownModuleFile](Export-MarkdownModuleFile.md) -- [Import-MarkdownModuleFile](Import-MarkdownModuleFile.md) diff --git a/v2docs/Microsoft.PowerShell.PlatyPS/Import-MamlHelp.md b/v2docs/Microsoft.PowerShell.PlatyPS/Import-MamlHelp.md deleted file mode 100644 index 731a4542..00000000 --- a/v2docs/Microsoft.PowerShell.PlatyPS/Import-MamlHelp.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -document type: cmdlet -external help file: Microsoft.PowerShell.PlatyPS.dll-Help.xml -HelpUri: '' -Locale: en-US -Module Name: Microsoft.PowerShell.PlatyPS -ms.custom: OPS12 -ms.date: 10/14/2024 -PlatyPS schema version: 2024-05-01 -title: Import-MamlHelp ---- - -# Import-MamlHelp - -## SYNOPSIS - -Imports MAML help from a file and creates **CommandHelp** objects for each command in the file. - -## SYNTAX - -### Path (Default) - -``` -Import-MamlHelp [-Path] <string[]> [<CommonParameters>] -``` - -### LiteralPath - -``` -Import-MamlHelp -LiteralPath <string[]> [<CommonParameters>] -``` - -## ALIASES - -## DESCRIPTION - -This command can be used to create **CommandHelp** objects from MAML help files. These objects can -be used to generate Markdown help files. You can also use this command to test the validity of the -MAML help files. - -## EXAMPLES - -### Example 1 - -```powershell -Import-MamlHelp -Path .\maml\Microsoft.PowerShell.PlatyPS.dll-Help.xml -``` - -## PARAMETERS - -### -LiteralPath - -The path to the MAML help file. Specifies a path to one or more locations. The value of LiteralPath -is used exactly as it's typed. No characters are interpreted as wildcards. If the path includes -escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not -to interpret any characters as escape sequences. - -For more information, see -[about_Quoting_Rules](/powershell/module/microsoft.powershell.core/about/about_quoting_rules). - -```yaml -Type: System.String[] -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: LiteralPath - Position: Named - IsRequired: true - ValueFromPipeline: false - ValueFromPipelineByPropertyName: true - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Path - -The path to the MAML help file. Specifies a path to one or more locations. - -```yaml -Type: System.String[] -DefaultValue: '' -SupportsWildcards: true -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: Path - Position: 0 - IsRequired: true - ValueFromPipeline: true - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### CommonParameters - -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, --InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, --ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see -[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### System.String - -## OUTPUTS - -### Microsoft.PowerShell.PlatyPS.Model.CommandHelp - -## NOTES - -The MAML file format doesn't support all the information that can be stored in a **CommandHelp** -object. If you convert the imported information to markdown format, the resulting markdown file -is not a complete representation of the original command. - -## RELATED LINKS - -- [Export-MamlHelp](Export-MamlCommandHelp.md) diff --git a/v2docs/Microsoft.PowerShell.PlatyPS/Import-MarkdownCommandHelp.md b/v2docs/Microsoft.PowerShell.PlatyPS/Import-MarkdownCommandHelp.md deleted file mode 100644 index a57eb62e..00000000 --- a/v2docs/Microsoft.PowerShell.PlatyPS/Import-MarkdownCommandHelp.md +++ /dev/null @@ -1,156 +0,0 @@ ---- -document type: cmdlet -external help file: Microsoft.PowerShell.PlatyPS.dll-Help.xml -HelpUri: '' -Locale: en-US -Module Name: Microsoft.PowerShell.PlatyPS -ms.custom: OPS12 -ms.date: 10/14/2024 -PlatyPS schema version: 2024-05-01 -title: Import-MarkdownCommandHelp ---- - -# Import-MarkdownCommandHelp - -## SYNOPSIS - -Imports Markdown help content into **CommandHelp** objects. - -## SYNTAX - -### Path (Default) - -``` -Import-MarkdownCommandHelp [-Path] <string[]> [<CommonParameters>] -``` - -### LiteralPath - -``` -Import-MarkdownCommandHelp -LiteralPath <string[]> [<CommonParameters>] -``` - -## ALIASES - -## DESCRIPTION - -The command imports Markdown files containing command help and creates **CommandHelp** objects. The -**CommandHelp** object is a structured representation of the help content that can be used to export -to different formats. - -## EXAMPLES - -### Example 1 - Import all cmdlet Markdown files in a folder - -The following example import cmdlet Markdown files in a folder and converts them to **CommandHelp** -objects. These objects can be used to export to different formats. - -```powershell -$mdfiles = Measure-PlatyPSMarkdown -Path .\v2\Microsoft.PowerShell.PlatyPS\*.md -$mdfiles | Where-Object Filetype -match 'CommandHelp' | - Import-MarkdownCommandHelp -Path {$_.FilePath} | - Select-Object Title -``` - -```Output -Title ------ -Compare-CommandHelp -Export-MamlCommandHelp -Export-MarkdownCommandHelp -Export-MarkdownModuleFile -Export-YamlCommandHelp -Export-YamlModuleFile -Import-MamlHelp -Import-MarkdownCommandHelp -Import-MarkdownModuleFile -Import-YamlCommandHelp -Import-YamlModuleFile -Measure-PlatyPSMarkdown -New-CommandHelp -New-MarkdownCommandHelp -New-MarkdownModuleFile -Test-MarkdownCommandHelp -Update-CommandHelp -Update-MarkdownCommandHelp -Update-MarkdownModuleFile -``` - -## PARAMETERS - -### -LiteralPath - -Specifies a path to one or more locations containing markdown files. The value of **LiteralPath** is -used exactly as it's typed. No characters are interpreted as wildcards. If the path includes escape -characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to -interpret any characters as escape sequences. - -For more information, see -[about_Quoting_Rules](/powershell/module/microsoft.powershell.core/about/about_CommonParameters). - -```yaml -Type: System.String[] -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: LiteralPath - Position: Named - IsRequired: true - ValueFromPipeline: true - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Path - -Specifies the path to an item. This cmdlet gets the item at the specified location. Wildcard -characters are permitted. This parameter is required, but the parameter name Path is optional. - -Use a dot (`.`) to specify the current location. Use the wildcard character (`*`) to specify all -items in the current location. - -```yaml -Type: System.String[] -DefaultValue: '' -SupportsWildcards: true -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: Path - Position: 0 - IsRequired: true - ValueFromPipeline: true - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### CommonParameters - -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, --InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, --ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see -[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### System.String - -## OUTPUTS - -### Microsoft.PowerShell.PlatyPS.Model.CommandHelp - -## NOTES - -## RELATED LINKS - -- [Export-MarkdownCommandHelp](Export-MarkdownCommandHelp.md) -- [Export-YamlCommandHelp](Export-YamlCommandHelp.md) -- [Import-YamlCommandHelp](Import-YamlCommandHelp.md) diff --git a/v2docs/Microsoft.PowerShell.PlatyPS/Import-MarkdownModuleFile.md b/v2docs/Microsoft.PowerShell.PlatyPS/Import-MarkdownModuleFile.md deleted file mode 100644 index b431109f..00000000 --- a/v2docs/Microsoft.PowerShell.PlatyPS/Import-MarkdownModuleFile.md +++ /dev/null @@ -1,138 +0,0 @@ ---- -document type: cmdlet -external help file: Microsoft.PowerShell.PlatyPS.dll-Help.xml -HelpUri: '' -Locale: en-US -Module Name: Microsoft.PowerShell.PlatyPS -ms.custom: OPS12 -ms.date: 10/14/2024 -PlatyPS schema version: 2024-05-01 -title: Import-MarkdownModuleFile ---- - -# Import-MarkdownModuleFile - -## SYNOPSIS - -Imports a Markdown module file into a **ModuleHelp** object. - -## SYNTAX - -### Path (Default) - -``` -Import-MarkdownModuleFile [-Path] <string[]> [<CommonParameters>] -``` - -### LiteralPath - -``` -Import-MarkdownModuleFile -LiteralPath <string[]> [<CommonParameters>] -``` - -## ALIASES - -## DESCRIPTION - -The command imports Markdown files containing module help and creates **ModuleHelp** objects. The -**ModuleHelp** object is a structured representation of the help content that can be used to export -to different formats. - -## EXAMPLES - -### Example 1 - Convert - -```powershell -Import-MarkdownModuleFile .\v2\Microsoft.PowerShell.PlatyPS\Microsoft.PowerShell.PlatyPS.md -``` - -```Output -Metadata : {[document type, module], [HelpInfoUri, ], [Locale, en-US], [Module Guid, - 0bdcabef-a4b7-4a6d-bf7e-d879817ebbff]…} -Title : Microsoft.PowerShell.PlatyPS Module -Module : Microsoft.PowerShell.PlatyPS -ModuleGuid : 0bdcabef-a4b7-4a6d-bf7e-d879817ebbff -Description : This module contains cmdlets to help with the creation help content for PowerShell commands. -Locale : en-US -CommandGroups : {Microsoft.PowerShell.PlatyPS.ModuleCommandGroup} -Diagnostics : Microsoft.PowerShell.PlatyPS.Model.Diagnostics -``` - -## PARAMETERS - -### -LiteralPath - -Specifies a path to one or more locations containing markdown files. The value of **LiteralPath** is -used exactly as it's typed. No characters are interpreted as wildcards. If the path includes escape -characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to -interpret any characters as escape sequences. - -For more information, see -[about_Quoting_Rules](/powershell/module/microsoft.powershell.core/about/about_CommonParameters). - -```yaml -Type: System.String[] -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: LiteralPath - Position: Named - IsRequired: true - ValueFromPipeline: true - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Path - -Specifies the path to an item. This cmdlet gets the item at the specified location. Wildcard -characters are permitted. This parameter is required, but the parameter name Path is optional. - -Use a dot (`.`) to specify the current location. Use the wildcard character (`*`) to specify all -items in the current location. - -```yaml -Type: System.String[] -DefaultValue: '' -SupportsWildcards: true -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: Path - Position: 0 - IsRequired: true - ValueFromPipeline: true - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### CommonParameters - -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, --InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, --ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see -[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### System.String - -## OUTPUTS - -### Microsoft.PowerShell.PlatyPS.ModuleFileInfo - -## NOTES - -## RELATED LINKS - -- [Export-MarkdownModuleFile](Export-MarkdownModuleFile.md) -- [Export-YamlModuleFile](Export-YamlModuleFile.md) -- [Import-MarkdownModuleFile](Import-MarkdownModuleFile.md) diff --git a/v2docs/Microsoft.PowerShell.PlatyPS/Import-YamlCommandHelp.md b/v2docs/Microsoft.PowerShell.PlatyPS/Import-YamlCommandHelp.md deleted file mode 100644 index 65099ab1..00000000 --- a/v2docs/Microsoft.PowerShell.PlatyPS/Import-YamlCommandHelp.md +++ /dev/null @@ -1,177 +0,0 @@ ---- -document type: cmdlet -external help file: Microsoft.PowerShell.PlatyPS.dll-Help.xml -HelpUri: '' -Locale: en-US -Module Name: Microsoft.PowerShell.PlatyPS -ms.custom: OPS12 -ms.date: 10/14/2024 -PlatyPS schema version: 2024-05-01 -title: Import-YamlCommandHelp ---- - -# Import-YamlCommandHelp - -## SYNOPSIS - -Imports Yaml help content into **CommandHelp** objects. - -## SYNTAX - -### Path (Default) - -``` -Import-YamlCommandHelp [-Path] <string[]> [-AsDictionary] [<CommonParameters>] -``` - -### LiteralPath - -``` -Import-YamlCommandHelp -LiteralPath <string[]> [-AsDictionary] [<CommonParameters>] -``` - -## ALIASES - -## DESCRIPTION - -The command imports Yaml files containing command help and creates **CommandHelp** objects. The -**CommandHelp** object is a structured representation of the help content that can be used to export -to different formats. - -## EXAMPLES - -### Example 1 - Import all cmdlet Yaml files in a folder - -The following example import cmdlet Markdown files in a folder and converts them to **CommandHelp** -objects. These objects can be used to export to different formats. - -```powershell -Import-YamlCommandHelp -Path .\v2\yaml\*-*.yml | Select-Object Title -``` - -```Output -Title ------ -Compare-CommandHelp -Export-MamlCommandHelp -Export-MarkdownCommandHelp -Export-MarkdownModuleFile -Export-YamlCommandHelp -Export-YamlModuleFile -Import-MamlHelp -Import-MarkdownCommandHelp -Import-MarkdownModuleFile -Import-YamlCommandHelp -Import-YamlModuleFile -Measure-PlatyPSMarkdown -New-CommandHelp -New-MarkdownCommandHelp -New-MarkdownModuleFile -Test-MarkdownCommandHelp -Update-CommandHelp -Update-MarkdownCommandHelp -Update-MarkdownModuleFile -``` - -## PARAMETERS - -### -AsDictionary - -By default this cmdlet returns **CommandHelp** objects. When you use this parameter. the cmdlet -returns the same information as an **OrderedDictionary** object. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -LiteralPath - -Specifies a path to one or more Yaml command files. The value of LiteralPath is used exactly as it's -typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose -it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters -as escape sequences. - -For more information, see -[about_Quoting_Rules](/powershell/module/microsoft.powershell.core/about/about_quoting_rules). - -```yaml -Type: System.String[] -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: LiteralPath - Position: Named - IsRequired: true - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Path - -The path to the Yaml command file. Specifies a path to one or more locations. - -```yaml -Type: System.String[] -DefaultValue: '' -SupportsWildcards: true -ParameterValue: [] -Aliases: -- FullName -ParameterSets: -- Name: Path - Position: 0 - IsRequired: true - ValueFromPipeline: true - ValueFromPipelineByPropertyName: true - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### CommonParameters - -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, --InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, --ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see -[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### System.String - -## OUTPUTS - -### System.Collections.Specialized.OrderedDictionary - -This cmdlet returns an **OrderedDictionary** object when you use the **AsDictionary** parameter. - -### Microsoft.PowerShell.PlatyPS.Model.CommandHelp - -By default, this cmdlet returns **CommandHelp** objects. - -## NOTES - -## RELATED LINKS - -- [Export-YamlCommandHelp](Export-YamlCommandHelp.md) diff --git a/v2docs/Microsoft.PowerShell.PlatyPS/Import-YamlModuleFile.md b/v2docs/Microsoft.PowerShell.PlatyPS/Import-YamlModuleFile.md deleted file mode 100644 index 4298bb9c..00000000 --- a/v2docs/Microsoft.PowerShell.PlatyPS/Import-YamlModuleFile.md +++ /dev/null @@ -1,155 +0,0 @@ ---- -document type: cmdlet -external help file: Microsoft.PowerShell.PlatyPS.dll-Help.xml -HelpUri: '' -Locale: en-US -Module Name: Microsoft.PowerShell.PlatyPS -ms.custom: OPS12 -ms.date: 10/14/2024 -PlatyPS schema version: 2024-05-01 -title: Import-YamlModuleFile ---- - -# Import-YamlModuleFile - -## SYNOPSIS - -Imports a Yaml module file into a **ModuleHelp** object. - -## SYNTAX - -### Path (Default) - -``` -Import-YamlModuleFile [-Path] <string[]> [-AsDictionary] [<CommonParameters>] -``` - -### LiteralPath - -``` -Import-YamlModuleFile -LiteralPath <string[]> [-AsDictionary] [<CommonParameters>] -``` - -## ALIASES - -## DESCRIPTION - -The command imports Yaml files containing module help and creates **ModuleHelp** objects. The -**ModuleHelp** object is a structured representation of the help content that can be used to export -to different formats. - -## EXAMPLES - -### Example 1 - Import a Yaml module file to a **ModuleHelp** object - -```powershell -Import-YamlModuleFile .\v2\yaml\Microsoft.PowerShell.PlatyPS.yml -``` - -```Output -Metadata : {[document type, module], [HelpInfoUri, ], [Locale, en-US], [Module Guid, - 0bdcabef-a4b7-4a6d-bf7e-d879817ebbff]…} -Title : Microsoft.PowerShell.PlatyPS Module -Module : Microsoft.PowerShell.PlatyPS -ModuleGuid : 0bdcabef-a4b7-4a6d-bf7e-d879817ebbff -Description : This module contains cmdlets to help with the creation help content for PowerShell commands. -Locale : en-US -CommandGroups : {Microsoft.PowerShell.PlatyPS.ModuleCommandGroup} -Diagnostics : Microsoft.PowerShell.PlatyPS.Model.Diagnostics -``` - -## PARAMETERS - -### -AsDictionary - -By default, the command returns a **ModuleHelp** object. When you use this parameter, the command -returns the **ModuleHelp** data a dictionary object. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -LiteralPath - -Specifies a path to one or more Yaml module files. The value of **LiteralPath** is used exactly as -it's typed. No characters are interpreted as wildcards. If the path includes escape characters, -enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any -characters as escape sequences. - -For more information, see -[about_Quoting_Rules](/powershell/module/microsoft.powershell.core/about/about_CommonParameters). - -```yaml -Type: System.String[] -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: LiteralPath - Position: Named - IsRequired: true - ValueFromPipeline: true - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Path - -Specifies a path to one or more locations containing Yaml module files. - -```yaml -Type: System.String[] -DefaultValue: '' -SupportsWildcards: true -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: Path - Position: 0 - IsRequired: true - ValueFromPipeline: true - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### CommonParameters - -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, --InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, --ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see -[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### System.String - -## OUTPUTS - -### Microsoft.PowerShell.PlatyPS.ModuleFileInfo - -## NOTES - -## RELATED LINKS - -- [Import-MarkdownModuleFile](Import-MarkdownModuleFile.md) diff --git a/v2docs/Microsoft.PowerShell.PlatyPS/Measure-PlatyPSMarkdown.md b/v2docs/Microsoft.PowerShell.PlatyPS/Measure-PlatyPSMarkdown.md deleted file mode 100644 index 85d88709..00000000 --- a/v2docs/Microsoft.PowerShell.PlatyPS/Measure-PlatyPSMarkdown.md +++ /dev/null @@ -1,153 +0,0 @@ ---- -document type: cmdlet -external help file: Microsoft.PowerShell.PlatyPS.dll-Help.xml -HelpUri: '' -Locale: en-US -Module Name: Microsoft.PowerShell.PlatyPS -ms.custom: OPS12 -ms.date: 10/14/2024 -PlatyPS schema version: 2024-05-01 -title: Measure-PlatyPSMarkdown ---- - -# Measure-PlatyPSMarkdown - -## SYNOPSIS - -Determines the type of Markdown file. - -## SYNTAX - -### Path (Default) - -``` -Measure-PlatyPSMarkdown [-Path] <string[]> [<CommonParameters>] -``` - -### LiteralPath - -``` -Measure-PlatyPSMarkdown -LiteralPath <string[]> [<CommonParameters>] -``` - -## ALIASES - -## DESCRIPTION - -The command reads the content of the file and determines the type of content. The command returns a -**PlatyPSMarkdown** object that contains the content type and schema version of a PlatyPS markdown -file. This is useful for selecting just the files that contain **CommandHelp** or **ModuleHelp** -content. - -## EXAMPLES - -### Example 1 - Measure all Markdown files in a folder - -```powershell -Measure-PlatyPSMarkdown -Path .\v2\Microsoft.PowerShell.PlatyPS\*.md -``` - -```Output -Title Filetype Filepath ------ -------- -------- -Compare-CommandHelp CommandHelp, V2Schema D:\Git\PS-Src\platyPS\v2docs\v2\Microsoft.PowerShell.PlatyPS\Compare-CommandHelp.md -Export-MamlCommandHelp CommandHelp, V2Schema D:\Git\PS-Src\platyPS\v2docs\v2\Microsoft.PowerShell.PlatyPS\Export-MamlCommandHelp.md -Export-MarkdownCommandHelp CommandHelp, V2Schema D:\Git\PS-Src\platyPS\v2docs\v2\Microsoft.PowerShell.PlatyPS\Export-MarkdownCommandHelp.md -Export-MarkdownModuleFile CommandHelp, V2Schema D:\Git\PS-Src\platyPS\v2docs\v2\Microsoft.PowerShell.PlatyPS\Export-MarkdownModuleFile.md -Export-YamlCommandHelp CommandHelp, V2Schema D:\Git\PS-Src\platyPS\v2docs\v2\Microsoft.PowerShell.PlatyPS\Export-YamlCommandHelp.md -Export-YamlModuleFile CommandHelp, V2Schema D:\Git\PS-Src\platyPS\v2docs\v2\Microsoft.PowerShell.PlatyPS\Export-YamlModuleFile.md -Import-MamlHelp CommandHelp, V2Schema D:\Git\PS-Src\platyPS\v2docs\v2\Microsoft.PowerShell.PlatyPS\Import-MamlHelp.md -Import-MarkdownCommandHelp CommandHelp, V2Schema D:\Git\PS-Src\platyPS\v2docs\v2\Microsoft.PowerShell.PlatyPS\Import-MarkdownCommandHelp.md -Import-MarkdownModuleFile CommandHelp, V2Schema D:\Git\PS-Src\platyPS\v2docs\v2\Microsoft.PowerShell.PlatyPS\Import-MarkdownModuleFile.md -Import-YamlCommandHelp CommandHelp, V2Schema D:\Git\PS-Src\platyPS\v2docs\v2\Microsoft.PowerShell.PlatyPS\Import-YamlCommandHelp.md -Import-YamlModuleFile CommandHelp, V2Schema D:\Git\PS-Src\platyPS\v2docs\v2\Microsoft.PowerShell.PlatyPS\Import-YamlModuleFile.md -Measure-PlatyPSMarkdown CommandHelp, V2Schema D:\Git\PS-Src\platyPS\v2docs\v2\Microsoft.PowerShell.PlatyPS\Measure-PlatyPSMarkdown.md -Microsoft.PowerShell.PlatyPS Module ModuleFile, V2Schema D:\Git\PS-Src\platyPS\v2docs\v2\Microsoft.PowerShell.PlatyPS\Microsoft.PowerShell.PlatyPS.md -New-CommandHelp CommandHelp, V2Schema D:\Git\PS-Src\platyPS\v2docs\v2\Microsoft.PowerShell.PlatyPS\New-CommandHelp.md -New-MarkdownCommandHelp CommandHelp, V2Schema D:\Git\PS-Src\platyPS\v2docs\v2\Microsoft.PowerShell.PlatyPS\New-MarkdownCommandHelp.md -New-MarkdownModuleFile CommandHelp, V2Schema D:\Git\PS-Src\platyPS\v2docs\v2\Microsoft.PowerShell.PlatyPS\New-MarkdownModuleFile.md -Test-MarkdownCommandHelp CommandHelp, V2Schema D:\Git\PS-Src\platyPS\v2docs\v2\Microsoft.PowerShell.PlatyPS\Test-MarkdownCommandHelp.md -Update-CommandHelp CommandHelp, V2Schema D:\Git\PS-Src\platyPS\v2docs\v2\Microsoft.PowerShell.PlatyPS\Update-CommandHelp.md -Update-MarkdownCommandHelp CommandHelp, V2Schema D:\Git\PS-Src\platyPS\v2docs\v2\Microsoft.PowerShell.PlatyPS\Update-MarkdownCommandHelp.md -Update-MarkdownModuleFile CommandHelp, V2Schema D:\Git\PS-Src\platyPS\v2docs\v2\Microsoft.PowerShell.PlatyPS\Update-MarkdownModuleFile.md -``` - -## PARAMETERS - -### -LiteralPath - -Specifies a path to one or more Markdown files. The value of **LiteralPath** is used exactly as it's -typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose -it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters -as escape sequences. - -For more information, see -[about_Quoting_Rules](/powershell/module/microsoft.powershell.core/about/about_quoting_rules). - -```yaml -Type: System.String[] -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: LiteralPath - Position: Named - IsRequired: true - ValueFromPipeline: true - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Path - -The path to one or more Markdown files. Specifies a path to one or more locations. - -```yaml -Type: System.String[] -DefaultValue: '' -SupportsWildcards: true -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: Path - Position: 0 - IsRequired: true - ValueFromPipeline: true - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### CommonParameters - -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, --InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, --ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see -[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### System.String - -## OUTPUTS - -### Microsoft.PowerShell.PlatyPS.MarkdownProbeInfo - -## NOTES - -For old format markdown files, the command examines the frontmatter and H2 structure to determine -the content type. For new format markdown files, the command examines the `document type` key in the -frontmatter. - -The command doesn't validate the full structure of the markdown file. Use `Test-MarkdownCommandHelp` -to validate the structure of the markdown file. - -## RELATED LINKS - -- [Test-MarkdownCommandHelp](Test-MarkdownCommandHelp.md) diff --git a/v2docs/Microsoft.PowerShell.PlatyPS/Microsoft.PowerShell.PlatyPS.md b/v2docs/Microsoft.PowerShell.PlatyPS/Microsoft.PowerShell.PlatyPS.md deleted file mode 100644 index a4affd27..00000000 --- a/v2docs/Microsoft.PowerShell.PlatyPS/Microsoft.PowerShell.PlatyPS.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -document type: module -Help Version: 1.0.0.0 -HelpInfoUri: -Locale: en-US -Module Guid: 0bdcabef-a4b7-4a6d-bf7e-d879817ebbff -Module Name: Microsoft.PowerShell.PlatyPS -ms.custom: OPS12 -ms.date: 10/15/2024 -PlatyPS schema version: 2024-05-01 -title: Microsoft.PowerShell.PlatyPS Module ---- - -# Microsoft.PowerShell.PlatyPS Module - -## Description - -This module contains cmdlets to help with the creation help content for PowerShell commands. - -## Microsoft.PowerShell.PlatyPS Cmdlets - -### [Compare-CommandHelp](Compare-CommandHelp.md) - -Compares two **CommandHelp** objects and produces a detailed report showing the differences. - -### [Export-MamlCommandHelp](Export-MamlCommandHelp.md) - -Exports **CommandHelp** objects to a MAML file. - -### [Export-MarkdownCommandHelp](Export-MarkdownCommandHelp.md) - -Exports a **CommandHelp** object to a markdown file. - -### [Export-MarkdownModuleFile](Export-MarkdownModuleFile.md) - -Exports a **ModuleFileInfo** object to a markdown file. - -### [Export-YamlCommandHelp](Export-YamlCommandHelp.md) - -Exports **CommandHelp** objects to YAML files. - -### [Export-YamlModuleFile](Export-YamlModuleFile.md) - -Exports a **ModuleFileInfo** object to a Yaml file. - -### [Import-MamlHelp](Import-MamlHelp.md) - -Imports MAML help from a file and creates **CommandHelp** objects for each command in the file. - -### [Import-MarkdownCommandHelp](Import-MarkdownCommandHelp.md) - -Imports Markdown help content into **CommandHelp** objects. - -### [Import-MarkdownModuleFile](Import-MarkdownModuleFile.md) - -Imports a Markdown module file into a **ModuleHelp** object. - -### [Import-YamlCommandHelp](Import-YamlCommandHelp.md) - -Imports Yaml help content into **CommandHelp** objects. - -### [Import-YamlModuleFile](Import-YamlModuleFile.md) - -Imports a Yaml module file into a **ModuleHelp** object. - -### [Measure-PlatyPSMarkdown](Measure-PlatyPSMarkdown.md) - -Determines the type of Markdown file. - -### [New-CommandHelp](New-CommandHelp.md) - -Creates **CommandHelp** objects for a PowerShell command that's loaded in the session. - -### [New-MarkdownCommandHelp](New-MarkdownCommandHelp.md) - -Creates Markdown help files for PowerShell modules and commands. - -### [New-MarkdownModuleFile](New-MarkdownModuleFile.md) - -Creates the Markdown module file for a PowerShell module. - -### [Test-MarkdownCommandHelp](Test-MarkdownCommandHelp.md) - -Tests the structure of a Markdown help file. - -### [Update-CommandHelp](Update-CommandHelp.md) - -Updates an imported **CommandHelp** object with the information from session cmdlet of the same -name. - -### [Update-MarkdownCommandHelp](Update-MarkdownCommandHelp.md) - -Updates an imported Markdown command file with the information from session cmdlet of the same name. - -### [Update-MarkdownModuleFile](Update-MarkdownModuleFile.md) - -Updates the Markdown module file. - diff --git a/v2docs/Microsoft.PowerShell.PlatyPS/New-CommandHelp.md b/v2docs/Microsoft.PowerShell.PlatyPS/New-CommandHelp.md deleted file mode 100644 index 930b4418..00000000 --- a/v2docs/Microsoft.PowerShell.PlatyPS/New-CommandHelp.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -document type: cmdlet -external help file: Microsoft.PowerShell.PlatyPS.dll-Help.xml -HelpUri: '' -Locale: en-US -Module Name: Microsoft.PowerShell.PlatyPS -ms.custom: OPS12 -ms.date: 10/14/2024 -PlatyPS schema version: 2024-05-01 -title: New-CommandHelp ---- - -# New-CommandHelp - -## SYNOPSIS - -Creates **CommandHelp** objects for a PowerShell command that's loaded in the session. - -## SYNTAX - -### __AllParameterSets - -``` -New-CommandHelp [-CommandInfo] <CommandInfo[]> [<CommonParameters>] -``` - -## ALIASES - -## DESCRIPTION - -This cmdlet takes a list of one or more PowerShell commands and creates **CommandHelp** objects for -each command. The **CommandHelp** object is a structured representation of the help content that can -be used to export to different formats. - -## EXAMPLES - -### Example 1 - Creates a **CommandHelp** object for a cmdlet - -The following example creates a **CommandHelp** object for the `New-PSSession` cmdlet. The -`Get-Member` cmdlet is used to display the properties and methods of the **CommandHelp** object. - -```powershell -New-CommandHelp New-PSSession | Get-Member -``` - -```Output - TypeName: Microsoft.PowerShell.PlatyPS.Model.CommandHelp - -Name MemberType Definition ----- ---------- ---------- -Equals Method bool Equals(Microsoft.PowerShell.PlatyPS.Model.CommandHelp other)... -GetHashCode Method int GetHashCode() -GetType Method type GetType() -ToString Method string ToString() -TryGetParameter Method bool TryGetParameter(string name, [ref] Microsoft.PowerShell.Plat... -Aliases Property System.Collections.Generic.List[string] Aliases {get;} -Description Property string Description {get;set;} -Diagnostics Property Microsoft.PowerShell.PlatyPS.Model.Diagnostics Diagnostics {get;s... -Examples Property System.Collections.Generic.List[Microsoft.PowerShell.PlatyPS.Mode... -ExternalHelpFile Property string ExternalHelpFile {get;set;} -HasCmdletBinding Property bool HasCmdletBinding {get;set;} -HasWorkflowCommonParameters Property bool HasWorkflowCommonParameters {get;set;} -Inputs Property System.Collections.Generic.List[Microsoft.PowerShell.PlatyPS.Mode... -Locale Property cultureinfo Locale {get;set;} -Metadata Property ordered Metadata {get;set;} -ModuleGuid Property System.Nullable[guid] ModuleGuid {get;set;} -ModuleName Property string ModuleName {get;set;} -Notes Property string Notes {get;set;} -OnlineVersionUrl Property string OnlineVersionUrl {get;set;} -Outputs Property System.Collections.Generic.List[Microsoft.PowerShell.PlatyPS.Mode... -Parameters Property System.Collections.Generic.List[Microsoft.PowerShell.PlatyPS.Mode... -RelatedLinks Property System.Collections.Generic.List[Microsoft.PowerShell.PlatyPS.Mode... -SchemaVersion Property string SchemaVersion {get;set;} -Synopsis Property string Synopsis {get;set;} -Syntax Property System.Collections.Generic.List[Microsoft.PowerShell.PlatyPS.Mode... -Title Property string Title {get;set;} -``` - -## PARAMETERS - -### -CommandInfo - -A list of one or more PowerShell commands (cmdlets, functions, scripts). The cmdlet creates a -**CommandHelp** object for each command. - -```yaml -Type: System.Management.Automation.CommandInfo[] -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: 0 - IsRequired: true - ValueFromPipeline: true - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### CommonParameters - -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, --InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, --ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see -[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### System.Management.Automation.CommandInfo - -## OUTPUTS - -### Microsoft.PowerShell.PlatyPS.Model.CommandHelp - -## NOTES - -## RELATED LINKS - -- [Export-MarkdownCommandHelp](Export-MarkdownCommandHelp.md) -- [Export-YamlCommandHelp](Export-YamlCommandHelp.md) diff --git a/v2docs/Microsoft.PowerShell.PlatyPS/New-MarkdownCommandHelp.md b/v2docs/Microsoft.PowerShell.PlatyPS/New-MarkdownCommandHelp.md deleted file mode 100644 index 410643d3..00000000 --- a/v2docs/Microsoft.PowerShell.PlatyPS/New-MarkdownCommandHelp.md +++ /dev/null @@ -1,413 +0,0 @@ ---- -document type: cmdlet -external help file: Microsoft.PowerShell.PlatyPS.dll-Help.xml -HelpUri: '' -Locale: en-US -Module Name: Microsoft.PowerShell.PlatyPS -ms.custom: OPS12 -ms.date: 10/14/2024 -PlatyPS schema version: 2024-05-01 -title: New-MarkdownCommandHelp ---- - -# New-MarkdownCommandHelp - -## SYNOPSIS - -Creates Markdown help files for PowerShell modules and commands. - -## SYNTAX - -### __AllParameterSets - -``` -New-MarkdownCommandHelp -OutputFolder <string> [-CommandInfo <CommandInfo[]>] [-Encoding <Encoding>] - [-Force] [-HelpUri <string>] [-HelpInfoUri <string>] [-HelpVersion <version>] [-Locale <string>] - [-Metadata <hashtable>] [-ModuleInfo <psmoduleinfo[]>] [-WithModulePage] - [-AbbreviateParameterTypename] [-WhatIf] [-Confirm] [<CommonParameters>] -``` - -## ALIASES - -## DESCRIPTION - -Creates Markdown help files for PowerShell modules and commands. - -## EXAMPLES - -### Example 1 - Create Markdown help files for a module - -```powershell -$newMarkdownCommandHelpSplat = @{ - ModuleInfo = Get-Module Microsoft.PowerShell.PlatyPS - OutputFolder = '.' - HelpVersion = '1.0.0.0' - WithModulePage = $true -} -New-MarkdownCommandHelp @newMarkdownCommandHelpSplat -``` - -### Example 2 - Create Markdown help files from a list of commands - -```powershell -$newMarkdownCommandHelpSplat = @{ - CommandInfo = Get-Command -Module Microsoft.PowerShell.PlatyPS - OutputFolder = '.' - HelpVersion = '1.0.0.0' - WithModulePage = $true -} -New-MarkdownCommandHelp @newMarkdownCommandHelpSplat -``` - -## PARAMETERS - -### -AbbreviateParameterTypename - -By default, this command uses full type names in the parameter metadata and for the input and output -types. When you use this parameter, the cmdlet outputs short type names. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -CommandInfo - -A list of one or more commands to create help for. - -```yaml -Type: System.Management.Automation.CommandInfo[] -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: true - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Confirm - -Prompts you for confirmation before running the cmdlet. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: -- cf -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Encoding - -The encoding used when creating the output files. If not specified, the cmdlet uses value specified -by `$OutputEncoding`. - -```yaml -Type: System.Text.Encoding -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Force - -By default, this command doesn't overwrite existing files. When you use this parameter, the cmdlet -overwrites existing files. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -HelpInfoUri - -This parameter allows you to specify the URI used for updateable help. By default, the cmdlet uses -the HelpInfoUri specified in the module manifest. - -```yaml -Type: System.String -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -HelpUri - -This parameter allows you to specify the URI used for online help. By default, the cmdlet uses the -URI defined in the `[CmdletBinding()]` attribute for the command. - -```yaml -Type: System.String -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -HelpVersion - -This parameter allows you to specify the version of the help. The default value is `1.0.0.0`. This -version is written to the `HelpInfo.xml` file that is used for updateable help. - -```yaml -Type: System.Version -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Locale - -This parameter allows you to specify the language locale for the help files. By default, the cmdlet -uses the current **CultureInfo**. Use the `Get-Culture` cmdlet to see the current culture settings -on your system. - -```yaml -Type: System.String -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Metadata - -The metadata to add to the frontmatter of the markdown file. The metadata is a hashtable where the -you specify the key and value pairs to add to the frontmatter. New key names are added to the -existing frontmatter. The values of existing keys are overwritten. You can't overwrite the values of -the `document type` or `PlatyPS schema version` keys. If these keys are present in the hashtable, -the cmdlet ignores the values and outputs a warning. - -```yaml -Type: System.Collections.Hashtable -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -ModuleInfo - -A list of one or more modules to create help for. The cmdlet creates Markdown help files for all -commands in the module. The cmdlet creates a folder matching the name of the module in the output -location. All Markdown files are written to the module folder. - -```yaml -Type: System.Management.Automation.PSModuleInfo[] -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: true - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -OutputFolder - -Specifies the location of where the Markdown help files are written. The cmdlet creates a folder for -each module being processed. If the target command isn't associated with a module, the cmdlet -creates a the Markdown file in the root of the output folder. - -```yaml -Type: System.String -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: true - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -WhatIf - -Shows what would happen if the cmdlet runs. The cmdlet isn't run. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: -- wi -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -WithModulePage - -By default, this cmdlet only creates Markdown files for commands. When you use this parameter, the -cmdlet creates a Markdown file for the module. This Markdown file contains a list of all commands in -the module and metadata used to create the HelpInfo.xml file. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### CommonParameters - -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, --InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, --ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see -[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### System.Management.Automation.CommandInfo - -### System.Management.Automation.PSModuleInfo - -## OUTPUTS - -### System.IO.FileInfo - -## NOTES - -## RELATED LINKS - -- [Export-MarkdownCommandHelp](Export-MarkdownCommandHelp.md) diff --git a/v2docs/Microsoft.PowerShell.PlatyPS/New-MarkdownModuleFile.md b/v2docs/Microsoft.PowerShell.PlatyPS/New-MarkdownModuleFile.md deleted file mode 100644 index f9c3b39e..00000000 --- a/v2docs/Microsoft.PowerShell.PlatyPS/New-MarkdownModuleFile.md +++ /dev/null @@ -1,332 +0,0 @@ ---- -document type: cmdlet -external help file: Microsoft.PowerShell.PlatyPS.dll-Help.xml -HelpUri: '' -Locale: en-US -Module Name: Microsoft.PowerShell.PlatyPS -ms.custom: OPS12 -ms.date: 10/14/2024 -PlatyPS schema version: 2024-05-01 -title: New-MarkdownModuleFile ---- - -# New-MarkdownModuleFile - -## SYNOPSIS - -Creates the Markdown module file for a PowerShell module. - -## SYNTAX - -### __AllParameterSets - -``` -New-MarkdownModuleFile -OutputFolder <string> [-CommandHelp <CommandHelp[]>] [-Encoding <Encoding>] - [-Force] [-HelpUri <string>] [-HelpInfoUri <string>] [-HelpVersion <version>] [-Locale <string>] - [-Metadata <hashtable>] [-WhatIf] [-Confirm] [<CommonParameters>] -``` - -## ALIASES - -## DESCRIPTION - -This command creates the Markdown module file for a PowerShell module. The module file contains the -module metadata and a list of all commands with their synopsis descriptions. This file can be used -as the module landing page in a documentation set. The module metadata is used to by -`Export-MamlCommandHelp` to create the MAML help file for the module. - -## EXAMPLES - -### Example 1 - Create a new module file from a folder of command help files - -```powershell -$mdfiles = Measure-PlatyPSMarkdown -Path .\v2\Microsoft.PowerShell.PlatyPS\*.md -$mdfiles | Where-Object Filetype -match 'CommandHelp' | - Import-MarkdownCommandHelp -Path {$_.FilePath} | - New-MarkdownModuleFile -OutputFolder .\v2 -Force -``` - -```Output - Directory: D:\Docs\v2\Microsoft.PowerShell.PlatyPS - -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a--- 9/18/2024 1:49 PM 2129 Microsoft.PowerShell.PlatyPS.md -``` - -### Example 2 - Create a new module file from a list of commands - -```powershell -$newMarkdownCommandHelpSplat = @{ - CommandHelp = Get-Command -Module Microsoft.PowerShell.PlatyPS | New-CommandHelp - OutputFolder = '.\new' - Force = $true -} -New-MarkdownModuleFile @newMarkdownCommandHelpSplat -``` - -```Output - Directory: D:\Docs\new\Microsoft.PowerShell.PlatyPS - -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a--- 9/18/2024 1:49 PM 2129 Microsoft.PowerShell.PlatyPS.md -``` - -## PARAMETERS - -### -CommandHelp - -The **CommandHelp** objects to be included in the module file. You can pass the **CommandHelp** -object on the pipeline or by using the **Command** parameter. - -```yaml -Type: Microsoft.PowerShell.PlatyPS.Model.CommandHelp[] -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: true - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Confirm - -Prompts you for confirmation before running the cmdlet. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: -- cf -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Encoding - -The encoding used when creating the output files. If not specified, the cmdlet uses value specified -by `$OutputEncoding`. - -```yaml -Type: System.Text.Encoding -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Force - -By default, this command doesn't overwrite existing files. When you use this parameter, the cmdlet -overwrites existing files. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -HelpInfoUri - -This parameter allows you to specify the URI used for updateable help. By default, the cmdlet uses -the HelpInfoUri specified in the module manifest. - -```yaml -Type: System.String -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -HelpVersion - -This parameter allows you to specify the version of the help. The default value is `1.0.0.0`. This -version is written to the `HelpInfo.xml` file that is used for updateable help. - -```yaml -Type: System.Version -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Locale - -This parameter allows you to specify the language locale for the help files. By default, the cmdlet -uses the current **CultureInfo**. Use the `Get-Culture` cmdlet to see the current culture settings -on your system. - -```yaml -Type: System.String -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Metadata - -The metadata to add to the frontmatter of the markdown file. The metadata is a hashtable where the -you specify the key and value pairs to add to the frontmatter. New key names are added to the -existing frontmatter. The values of existing keys are overwritten. You can't overwrite the values of -the `document type` or `PlatyPS schema version` keys. If these keys are present in the hashtable, -the cmdlet ignores the values and outputs a warning. - -```yaml -Type: System.Collections.Hashtable -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -OutputFolder - -Specifies the location of where the Markdown module file is written. The cmdlet creates a folder for -each module based on the **CommandHelp** object being processed. - -```yaml -Type: System.String -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: true - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -WhatIf - -Shows what would happen if the cmdlet runs. The cmdlet isn't run. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: -- wi -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### CommonParameters - -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, --InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, --ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see -[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### Microsoft.PowerShell.PlatyPS.Model.CommandHelp - -## OUTPUTS - -### System.IO.FileInfo - -## NOTES - -## RELATED LINKS - -- [Export-MarkdownModuleFile](Export-MarkdownModuleFile.md) -- [Update-MarkdownModuleFile](Update-MarkdownModuleFile.md) diff --git a/v2docs/Microsoft.PowerShell.PlatyPS/Test-MarkdownCommandHelp.md b/v2docs/Microsoft.PowerShell.PlatyPS/Test-MarkdownCommandHelp.md deleted file mode 100644 index cf4a8d5b..00000000 --- a/v2docs/Microsoft.PowerShell.PlatyPS/Test-MarkdownCommandHelp.md +++ /dev/null @@ -1,177 +0,0 @@ ---- -document type: cmdlet -external help file: Microsoft.PowerShell.PlatyPS.dll-Help.xml -HelpUri: '' -Locale: en-US -Module Name: Microsoft.PowerShell.PlatyPS -ms.custom: OPS12 -ms.date: 10/14/2024 -PlatyPS schema version: 2024-05-01 -title: Test-MarkdownCommandHelp ---- - -# Test-MarkdownCommandHelp - -## SYNOPSIS - -Tests the structure of a Markdown help file. - -## SYNTAX - -### __AllParameterSets - -``` -Test-MarkdownCommandHelp [-FullName] <string[]> [-DetailView] [<CommonParameters>] -``` - -### Item - -``` -Test-MarkdownCommandHelp [-Path] <string[]> [-DetailView] [<CommonParameters>] -``` - -### Literal - -``` -Test-MarkdownCommandHelp -LiteralPath <string[]> [-DetailView] [<CommonParameters>] -``` - -## ALIASES - -## DESCRIPTION - -This command reads a Markdown help file and validates the structure of the help content by checking -for the presence of required elements in the proper order. The command returns `$true` if the file -passes validation. The **DetailView** parameter can be used to display more detailed validation -information. - -## EXAMPLES - -### Example 1 - Test a Markdown help file - -For this example, we test the structure of a Markdown Module help file. This test fails because the -command expects to test a Markdown Command help file. - -```powershell -Test-MarkdownCommandHelp .\v2\Microsoft.PowerShell.PlatyPS\Microsoft.PowerShell.PlatyPS.md -DetailView -``` - -The output shows the kind of information you can expect from the **DetailView** parameter. - -```Output -Test-MarkdownCommandHelp - Valid: False - File: D:\Git\PS-Src\platyPS\v2docs\v2\Microsoft.PowerShell.PlatyPS\Microsoft.PowerShell.PlatyPS.md - -Messages: - PASS: First element is a thematic break - FAIL: SYNOPSIS not found. - FAIL: SYNTAX not found. - FAIL: DESCRIPTION not found. - FAIL: EXAMPLES not found. - FAIL: PARAMETERS not found. - FAIL: INPUTS not found. - FAIL: OUTPUTS not found. - FAIL: NOTES not found. - FAIL: RELATED LINKS not found. -``` - -## PARAMETERS - -### -DetailView - -Instructs the command to output detailed validation information. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -LiteralPath - -Specifies a path to one or more command markdown files. The value of **LiteralPath** is used exactly -as it's typed. No characters are interpreted as wildcards. If the path includes escape characters, -enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any -characters as escape sequences. - -For more information, see -[about_Quoting_Rules](/powershell/module/microsoft.powershell.core/about/about_CommonParameters). - -```yaml -Type: System.String[] -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: -- PSPath -- LP -ParameterSets: -- Name: Literal - Position: Named - IsRequired: true - ValueFromPipeline: false - ValueFromPipelineByPropertyName: true - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Path - -The path to the Markdown help file to test. - -```yaml -Type: System.String[] -DefaultValue: '' -SupportsWildcards: true -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: Item - Position: 0 - IsRequired: true - ValueFromPipeline: true - ValueFromPipelineByPropertyName: true - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### CommonParameters - -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, --InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, --ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see -[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### System.String - -## OUTPUTS - -### System.Boolean - -### Microsoft.PowerShell.PlatyPS.MarkdownCommandHelpValidationResult - -## NOTES - -## RELATED LINKS - -- [Export-MarkdownCommandHelp](Export-MarkdownCommandHelp.md) -- [New-MarkdownCommandHelp](New-MarkdownCommandHelp.md) diff --git a/v2docs/Microsoft.PowerShell.PlatyPS/Update-CommandHelp.md b/v2docs/Microsoft.PowerShell.PlatyPS/Update-CommandHelp.md deleted file mode 100644 index 615a93c2..00000000 --- a/v2docs/Microsoft.PowerShell.PlatyPS/Update-CommandHelp.md +++ /dev/null @@ -1,177 +0,0 @@ ---- -document type: cmdlet -external help file: Microsoft.PowerShell.PlatyPS.dll-Help.xml -HelpUri: '' -Locale: en-US -Module Name: Microsoft.PowerShell.PlatyPS -ms.custom: OPS12 -ms.date: 10/14/2024 -PlatyPS schema version: 2024-05-01 -title: Update-CommandHelp ---- - -# Update-CommandHelp - -## SYNOPSIS - -Updates an imported **CommandHelp** object with the information from session cmdlet of the same -name. - -## SYNTAX - -### Path (Default) - -``` -Update-CommandHelp [-Path] <string[]> [-WhatIf] [-Confirm] [<CommonParameters>] -``` - -### LiteralPath - -``` -Update-CommandHelp -LiteralPath <string[]> [-WhatIf] [-Confirm] [<CommonParameters>] -``` - -## ALIASES - -## DESCRIPTION - -This cmdlet imports a **CommandHelp** object from a Markdown file and updates the object with the -information from the session cmdlet of the same name. The updated object can then be re-exported to -update the source Markdown file. - -## EXAMPLES - -### Example 1 - -```powershell -$mdfiles = Measure-PlatyPSMarkdown -Path .\v1\Microsoft.PowerShell.PlatyPS\*.md -$cmdobj = $mdfiles | Where-Object Filetype -match 'CommandHelp' | - Update-CommandHelp -Path {$_.FilePath} -$cmdobj.count -``` - -```Output -19 -``` - -## PARAMETERS - -### -Confirm - -Prompts you for confirmation before running the cmdlet. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: -- cf -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -LiteralPath - -Specifies a path to one or more markdown command files. The value of **LiteralPath** is used exactly -as it's typed. No characters are interpreted as wildcards. If the path includes escape characters, -enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any -characters as escape sequences. - -For more information, see -[about_Quoting_Rules](/powershell/module/microsoft.powershell.core/about/about_CommonParameters). - -```yaml -Type: System.String[] -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: LiteralPath - Position: Named - IsRequired: true - ValueFromPipeline: true - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Path - -Specifies the path to one or more Markdown command file. Wildcard characters are permitted. - -```yaml -Type: System.String[] -DefaultValue: '' -SupportsWildcards: true -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: Path - Position: 0 - IsRequired: true - ValueFromPipeline: true - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -WhatIf - -Shows what would happen if the cmdlet runs. The cmdlet isn't run. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: -- wi -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### CommonParameters - -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, --InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, --ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see -[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### System.String - -## OUTPUTS - -### Microsoft.PowerShell.PlatyPS.Model.CommandHelp - -## NOTES - -This command is similar to the `Update-MarkdownCommandHelp` cmdlet, but it updates the -**CommandHelp** object in memory instead of updating the source Markdown file. - -## RELATED LINKS - -- [Update-MarkdownCommandHelp](Update-MarkdownCommandHelp.md) diff --git a/v2docs/Microsoft.PowerShell.PlatyPS/Update-MarkdownCommandHelp.md b/v2docs/Microsoft.PowerShell.PlatyPS/Update-MarkdownCommandHelp.md deleted file mode 100644 index c2e18770..00000000 --- a/v2docs/Microsoft.PowerShell.PlatyPS/Update-MarkdownCommandHelp.md +++ /dev/null @@ -1,218 +0,0 @@ ---- -document type: cmdlet -external help file: Microsoft.PowerShell.PlatyPS.dll-Help.xml -HelpUri: '' -Locale: en-US -Module Name: Microsoft.PowerShell.PlatyPS -ms.custom: OPS12 -ms.date: 10/14/2024 -PlatyPS schema version: 2024-05-01 -title: Update-MarkdownCommandHelp ---- - -# Update-MarkdownCommandHelp - -## SYNOPSIS - -Updates an imported Markdown command file with the information from session cmdlet of the same name. - -## SYNTAX - -### Path (Default) - -``` -Update-MarkdownCommandHelp [-Path] <string[]> [-NoBackup] [-PassThru] [-WhatIf] [-Confirm] - [<CommonParameters>] -``` - -### LiteralPath - -``` -Update-MarkdownCommandHelp -LiteralPath <string[]> [-NoBackup] [-PassThru] [-WhatIf] [-Confirm] - [<CommonParameters>] -``` - -## ALIASES - -## DESCRIPTION - -This cmdlet imports a **CommandHelp** object from a Markdown file and updates the object with the -information from the session cmdlet of the same name, then rewrites the Markdown file with the -updated information. - -## EXAMPLES - -### Example 1 - -```powershell -$mdfiles = Measure-PlatyPSMarkdown -Path .\v1\Microsoft.PowerShell.PlatyPS\*.md -$mdfiles | Where-Object Filetype -match 'CommandHelp' | - Update-MarkdownCommandHelp -Path {$_.FilePath} -``` - -## PARAMETERS - -### -Confirm - -Prompts you for confirmation before running the cmdlet. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: -- cf -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -LiteralPath - -Specifies a path to one or more markdown command files. The value of **LiteralPath** is used exactly -as it's typed. No characters are interpreted as wildcards. If the path includes escape characters, -enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any -characters as escape sequences. - -For more information, see -[about_Quoting_Rules](/powershell/module/microsoft.powershell.core/about/about_CommonParameters). - -```yaml -Type: System.String[] -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: LiteralPath - Position: Named - IsRequired: true - ValueFromPipeline: true - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -NoBackup - -By default, the cmdlet creates a backup of the original Markdown file before updating it. Use this -parameter to suppress the creation of the backup file. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -PassThru - -By default, this cmdlet doesn't generate any output. Use this parameter to return the updated file -object. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Path - -Specifies the path to one or more Markdown command file. Wildcard characters are permitted. - -```yaml -Type: System.String[] -DefaultValue: '' -SupportsWildcards: true -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: Path - Position: 0 - IsRequired: true - ValueFromPipeline: true - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -WhatIf - -Shows what would happen if the cmdlet runs. The cmdlet isn't run. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: -- wi -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### CommonParameters - -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, --InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, --ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see -[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### System.String - -## OUTPUTS - -### System.IO.FileInfo - -## NOTES - -This command is similar to the `Update-CommandHelp` cmdlet, but it updates the source Markdown file. - -## RELATED LINKS - -- [Update-CommandHelp](Update-CommandHelp.md) diff --git a/v2docs/Microsoft.PowerShell.PlatyPS/Update-MarkdownModuleFile.md b/v2docs/Microsoft.PowerShell.PlatyPS/Update-MarkdownModuleFile.md deleted file mode 100644 index eaaa5f96..00000000 --- a/v2docs/Microsoft.PowerShell.PlatyPS/Update-MarkdownModuleFile.md +++ /dev/null @@ -1,360 +0,0 @@ ---- -document type: cmdlet -external help file: Microsoft.PowerShell.PlatyPS.dll-Help.xml -HelpUri: '' -Locale: en-US -Module Name: Microsoft.PowerShell.PlatyPS -ms.custom: OPS12 -ms.date: 10/14/2024 -PlatyPS schema version: 2024-05-01 -title: Update-MarkdownModuleFile ---- - -# Update-MarkdownModuleFile - -## SYNOPSIS - -Updates the Markdown module file. - -## SYNTAX - -### path - -``` -Update-MarkdownModuleFile [-Path] <string> [-CommandHelp] <CommandHelp[]> [-Encoding <Encoding>] - [-Force] [-HelpUri <string>] [-HelpInfoUri <string>] [-HelpVersion <version>] [-Locale <string>] - [-Metadata <hashtable>] [-NoBackup] [-WhatIf] [-Confirm] [<CommonParameters>] -``` - -### literalpath - -``` -Update-MarkdownModuleFile [-CommandHelp] <CommandHelp[]> -LiteralPath <string> - [-Encoding <Encoding>] [-Force] [-HelpUri <string>] [-HelpInfoUri <string>] - [-HelpVersion <version>] [-Locale <string>] [-Metadata <hashtable>] [-NoBackup] [-WhatIf] - [-Confirm] [<CommonParameters>] -``` - -## ALIASES - -## DESCRIPTION - -This cmdlet updates a Markdown module file with **CommandHelp** object information imported from -Markdown command files. - -## EXAMPLES - -### Example 1 - Update a module file from new command help files - -```powershell -$mdfiles = Measure-PlatyPSMarkdown -Path .\Microsoft.PowerShell.PlatyPS\*.md -$mdfiles | Where-Object Filetype -match 'CommandHelp' | - Import-MarkdownCommandHelp -Path {$_.FilePath} | - Update-MarkdownModuleFile -Path .\Microsoft.PowerShell.PlatyPS\Microsoft.PowerShell.PlatyPS.md -``` - -## PARAMETERS - -### -CommandHelp - -The **CommandHelp** objects to export. You can pass the **CommandHelp** object on the pipeline or by -using this parameter. - -```yaml -Type: Microsoft.PowerShell.PlatyPS.Model.CommandHelp[] -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: 1 - IsRequired: true - ValueFromPipeline: true - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Confirm - -Prompts you for confirmation before running the cmdlet. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: -- cf -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Encoding - -The encoding to use when writing the markdown file. If no value is specified, encoding defaults to -the value of the `$OutputEncoding` preference variable. - -```yaml -Type: System.Text.Encoding -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Force - -Use the **Force** parameter to overwrite the output file if it already exists. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -HelpInfoUri - -This parameter allows you to specify the URI used for updateable help. By default, the cmdlet uses -the HelpInfoUri specified in the module manifest. - -```yaml -Type: System.String -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -HelpVersion - -This parameter allows you to specify the version of the help. The default value is `1.0.0.0`. This -version is written to the `HelpInfo.xml` file that is used for updateable help. - -```yaml -Type: System.Version -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -LiteralPath - -Specifies a path to one or more module markdown files. The value of **LiteralPath** is used exactly -as it's typed. No characters are interpreted as wildcards. If the path includes escape characters, -enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any -characters as escape sequences. - -For more information, see -[about_Quoting_Rules](/powershell/module/microsoft.powershell.core/about/about_CommonParameters). - -```yaml -Type: System.String -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: literalpath - Position: Named - IsRequired: true - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Locale - -This parameter allows you to specify the language locale for the help files. By default, the cmdlet -uses the current **CultureInfo**. Use the `Get-Culture` cmdlet to see the current culture settings -on your system. - -```yaml -Type: System.String -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Metadata - -The metadata to add to the frontmatter of the markdown file. The metadata is a hashtable where the -you specify the key and value pairs to add to the frontmatter. New key names are added to the -existing frontmatter. The values of existing keys are overwritten. You can't overwrite the values of -the `document type` or `PlatyPS schema version` keys. If these keys are present in the hashtable, -the cmdlet ignores the values and outputs a warning. - -```yaml -Type: System.Collections.Hashtable -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -NoBackup - -By default, the cmdlet creates a backup of the original Markdown file before updating it. Use this -parameter to suppress the creation of the backup file. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Path - -Specifies a path to one or more module markdown files. - -```yaml -Type: System.String -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: [] -ParameterSets: -- Name: path - Position: 0 - IsRequired: true - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -WhatIf - -Shows what would happen if the cmdlet runs. The cmdlet isn't run. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -ParameterValue: [] -Aliases: -- wi -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### CommonParameters - -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, --InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, --ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see -[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### Microsoft.PowerShell.PlatyPS.Model.CommandHelp - -## OUTPUTS - -### System.IO.FileInfo - -## NOTES - -## RELATED LINKS - -- [New-MarkdownModuleFile](New-MarkdownModuleFile.md)