diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..543f158e --- /dev/null +++ b/.gitattributes @@ -0,0 +1,7 @@ +# Deterministic line endings across platforms +*.md text eol=lf +*.yml text eol=lf +*.yaml text eol=lf +*.ps1 text eol=lf +*.psm1 text eol=lf +*.psd1 text eol=lf \ No newline at end of file diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1e0f8672..f70785af 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -41,3 +41,77 @@ jobs: with: name: test-results-${{ matrix.os }} path: artifacts/test-results.xml + + docs-cmdlet-reference: + name: Verify cmdlet reference is up to date + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - name: Install platyPS + shell: pwsh + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + + # Ensure PSGallery does not prompt (non-interactive CI) + if (Get-Command -Name Set-PSRepository -ErrorAction SilentlyContinue) { + try { + Set-PSRepository -Name PSGallery -InstallationPolicy Trusted -ErrorAction Stop + } catch { + # Ignore if not supported in this environment + } + } + + Install-Module -Name platyPS -RequiredVersion 0.14.2 -Scope CurrentUser -Force -AllowClobber -ErrorAction Stop + + - name: Debug platyPS version + shell: pwsh + run: | + Get-Module -ListAvailable platyPS | Sort-Object Version -Descending | Select-Object -First 1 | Format-List Name,Version,Path + + - name: Generate cmdlet reference + shell: pwsh + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + pwsh -NoProfile -File ./tools/Generate-IdleCmdletReference.ps1 + + - name: Verify working tree clean + shell: bash + run: | + set -euo pipefail + echo "== git status ==" + git status --porcelain || true + + echo "== git diff (first 200 lines) ==" + git diff | sed -n '1,200p' || true + + git diff --exit-code + + docs-step-reference: + name: Verify step reference is up to date + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - name: Generate step reference + shell: pwsh + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + pwsh -NoProfile -File ./tools/Generate-IdleStepReference.ps1 + + - name: Verify working tree clean + shell: bash + run: | + set -euo pipefail + echo "== git status ==" + git status --porcelain || true + + echo "== git diff (first 200 lines) ==" + git diff | sed -n '1,200p' || true + + git diff --exit-code diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6387aef2..59dd7032 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -133,6 +133,131 @@ A contribution is complete when: --- +## Generated cmdlet reference (platyPS) + +IdLE maintains a generated cmdlet reference under: + +- `docs/reference/cmdlets.md` (index page) +- `docs/reference/cmdlets/*.md` (one file per cmdlet) + +These files are generated from comment-based help in the PowerShell source. **Do not edit the generated files by hand.** +Instead, update the comment-based help of the relevant public function/cmdlet and regenerate the reference. + +### platyPS version pinning + +The cmdlet reference is generated using **platyPS**. + +To ensure deterministic output across platforms and CI environments, the CI pipeline +**pins a specific platyPS version**. + +Do not upgrade platyPS casually. + +If you intentionally want to upgrade platyPS: + +1. Update the pinned version in the CI workflow. +2. Regenerate the cmdlet reference locally using the same version. +3. Commit the regenerated files under `docs/reference/cmdlets/`. +4. Verify that CI passes without diffs. + +This avoids documentation drift caused by formatting or template changes between platyPS versions. + +### When to regenerate + +Regenerate the cmdlet reference when you change any of the following for exported/public commands: + +- Add/remove/rename a public cmdlet/function +- Add/remove/rename parameters (including parameter sets) +- Change comment-based help: synopsis/description/parameters/examples + +### How to regenerate locally + +From the repository root: + +```powershell +pwsh ./tools/Generate-IdleCmdletReference.ps1 +``` + +If `platyPS` is not installed yet, you can install it automatically (requires internet access): + +```powershell +pwsh ./tools/Generate-IdleCmdletReference.ps1 -InstallPlatyPS +``` + +Commit the changed files under `docs/reference/` as part of the same PR that introduced the cmdlet/help changes. + +### CI enforcement (required status check) + +The CI pipeline verifies that the generated cmdlet reference is up to date. If you change public cmdlets or their +comment-based help and forget to regenerate the docs, the workflow **"Verify cmdlet reference is up to date"** will fail. + +To fix a failing PR: + +1. Run the generator locally from the repo root: + + ```powershell + pwsh ./tools/Generate-IdleCmdletReference.ps1 + ``` + + If needed (first time only): + + ```powershell + pwsh ./tools/Generate-IdleCmdletReference.ps1 -InstallPlatyPS + ``` + +2. Commit the updated files under `docs/reference/` and push to your branch. + +Repository maintainers should configure branch protection so that required status checks include this workflow. This ensures +generated docs cannot drift from the exported cmdlets. + +## Generated step reference + +IdLE maintains a generated step reference under: + +- `docs/reference/steps.md` + +The file is generated from step implementations in `IdLE.Steps.*` and their comment-based help. +**Do not edit the generated file by hand.** Update the step help/source and regenerate the reference. + +### When to regenerate + +Regenerate the step reference when you change any of the following: + +- Add/remove/rename a step implementation (`Invoke-IdleStep*`) +- Change step behavior that affects documented inputs (With.* keys), contracts, idempotency, or emitted events +- Update comment-based help of step implementations + +### How to regenerate locally + +From the repository root: + +```powershell +pwsh ./tools/Generate-IdleStepReference.ps1 +``` + +Commit the updated `docs/reference/steps.md` as part of the same PR that introduced the step changes. + +### CI enforcement (required status check) + +The CI pipeline verifies that the generated step reference is up to date. If you change steps and forget to regenerate the docs, +the workflow **"Verify step reference is up to date"** will fail. + +To fix a failing PR: + +1. Run the generator locally: + + ```powershell + pwsh ./tools/Generate-IdleStepReference.ps1 + ``` + +2. Commit the updated `docs/reference/steps.md` and push to your branch. + +Repository maintainers should configure branch protection so that required status checks include this workflow. + + + + + + ## Documentation Keep docs short and linkable: diff --git a/docs/_sidebar.md b/docs/_sidebar.md index f54db79f..1543de18 100644 --- a/docs/_sidebar.md +++ b/docs/_sidebar.md @@ -12,6 +12,10 @@ - [Steps](usage/steps.md) - [Providers](usage/providers.md) +### Reference +- [Cmdlet Reference](docs/reference/cmdlets.md) +- [Step Catalog](docs/reference/steps.md) + ### Advanced - [Architecture](advanced/architecture.md) - [Security](advanced/security.md) diff --git a/docs/index.md b/docs/index.md index 4748d1ba..dc70a525 100644 --- a/docs/index.md +++ b/docs/index.md @@ -13,11 +13,16 @@ for identity and account processes (Joiner / Mover / Leaver) built for **PowerSh - [Getting started: Installation](getting-started/installation.md) - [Getting started: Quickstart](getting-started/quickstart.md) -## Topics +## Usage -- [Usage: Workflows](usage/workflows.md) -- [Usage: Steps](usage/steps.md) -- [Usage: Providers](usage/providers.md) +- [Workflows](usage/workflows.md) +- [Steps](usage/steps.md) +- [Providers](usage/providers.md) + +## Reference + +- [Cmdlet Reference](docs/reference/cmdlets.md) +- [Step Catalog](docs/reference/steps.md) ## Advanced diff --git a/docs/reference/cmdlets.md b/docs/reference/cmdlets.md new file mode 100644 index 00000000..f833319b --- /dev/null +++ b/docs/reference/cmdlets.md @@ -0,0 +1,13 @@ +# Cmdlet Reference + +> Generated file. Do not edit by hand. +> Source: tools/Generate-IdleCmdletReference.ps1 + +This page links the generated per-cmdlet reference pages and includes their synopsis. + +| Cmdlet | Synopsis | +| --- | --- | +| [Invoke-IdlePlan](cmdlets/Invoke-IdlePlan.md) | Executes an IdLE plan. | +| [New-IdleLifecycleRequest](cmdlets/New-IdleLifecycleRequest.md) | Creates a lifecycle request object. | +| [New-IdlePlan](cmdlets/New-IdlePlan.md) | Creates a deterministic plan from a lifecycle request and a workflow definition. | +| [Test-IdleWorkflow](cmdlets/Test-IdleWorkflow.md) | Validates an IdLE workflow definition file. | diff --git a/docs/reference/cmdlets/Invoke-IdlePlan.md b/docs/reference/cmdlets/Invoke-IdlePlan.md new file mode 100644 index 00000000..71da2505 --- /dev/null +++ b/docs/reference/cmdlets/Invoke-IdlePlan.md @@ -0,0 +1,135 @@ +--- +external help file: IdLE-help.xml +Module Name: IdLE +online version: +schema: 2.0.0 +--- + +# Invoke-IdlePlan + +## SYNOPSIS +Executes an IdLE plan. + +## SYNTAX + +``` +Invoke-IdlePlan [-Plan] [[-Providers] ] [[-EventSink] ] + [-ProgressAction ] [-WhatIf] [-Confirm] [] +``` + +## DESCRIPTION +Executes a plan deterministically and emits structured events. +Delegates execution to IdLE.Core. + +## EXAMPLES + +### EXAMPLE 1 +``` +Invoke-IdlePlan -Plan $plan -Providers $providers +``` + +## PARAMETERS + +### -Plan +The plan object created by New-IdlePlan. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Providers +Provider registry/collection passed through to execution. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -EventSink +Optional external event sink for streaming. +Must be an object with a WriteEvent(event) method. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +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: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ProgressAction +{{ Fill ProgressAction Description }} + +```yaml +Type: ActionPreference +Parameter Sets: (All) +Aliases: proga + +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 + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/docs/reference/cmdlets/New-IdleLifecycleRequest.md b/docs/reference/cmdlets/New-IdleLifecycleRequest.md new file mode 100644 index 00000000..6c39d42a --- /dev/null +++ b/docs/reference/cmdlets/New-IdleLifecycleRequest.md @@ -0,0 +1,157 @@ +--- +external help file: IdLE-help.xml +Module Name: IdLE +online version: +schema: 2.0.0 +--- + +# New-IdleLifecycleRequest + +## SYNOPSIS +Creates a lifecycle request object. + +## SYNTAX + +``` +New-IdleLifecycleRequest [-LifecycleEvent] [[-CorrelationId] ] [[-Actor] ] + [[-IdentityKeys] ] [[-DesiredState] ] [[-Changes] ] + [-ProgressAction ] [] +``` + +## DESCRIPTION +Creates and normalizes an IdLE LifecycleRequest representing business intent +(e.g. +Joiner/Mover/Leaver). +CorrelationId is generated if missing. +Actor is optional. +Changes is optional and stays $null when omitted. + +## EXAMPLES + +### EXAMPLE 1 +``` +New-IdleLifecycleRequest -LifecycleEvent Joiner -CorrelationId (New-Guid) -IdentityKeys @{ EmployeeId = '12345' } +``` + +## PARAMETERS + +### -LifecycleEvent +The lifecycle event name (e.g. +Joiner, Mover, Leaver). + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -CorrelationId +Correlation identifier for audit/event correlation. +Generated if missing. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Actor +Optional actor claim who initiated the request. +Not required by the core engine in V1. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -IdentityKeys +A hashtable of system-neutral identity keys (e.g. +EmployeeId, UPN, ObjectId). + +```yaml +Type: Hashtable +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: @{} +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DesiredState +A hashtable describing the desired state (attributes, entitlements, etc.). + +```yaml +Type: Hashtable +Parameter Sets: (All) +Aliases: + +Required: False +Position: 5 +Default value: @{} +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Changes +Optional hashtable describing changes (typically used for Mover lifecycle events). + +```yaml +Type: Hashtable +Parameter Sets: (All) +Aliases: + +Required: False +Position: 6 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ProgressAction +{{ Fill ProgressAction Description }} + +```yaml +Type: ActionPreference +Parameter Sets: (All) +Aliases: proga + +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 + +## OUTPUTS + +### IdleLifecycleRequest +## NOTES + +## RELATED LINKS diff --git a/docs/reference/cmdlets/New-IdlePlan.md b/docs/reference/cmdlets/New-IdlePlan.md new file mode 100644 index 00000000..1e3b6b1e --- /dev/null +++ b/docs/reference/cmdlets/New-IdlePlan.md @@ -0,0 +1,104 @@ +--- +external help file: IdLE-help.xml +Module Name: IdLE +online version: +schema: 2.0.0 +--- + +# New-IdlePlan + +## SYNOPSIS +Creates a deterministic plan from a lifecycle request and a workflow definition. + +## SYNTAX + +``` +New-IdlePlan [-WorkflowPath] [-Request] [[-Providers] ] + [-ProgressAction ] [] +``` + +## DESCRIPTION +Delegates plan building to IdLE.Core and returns a plan artifact. +Providers are passed through for later increments. + +## EXAMPLES + +### EXAMPLE 1 +``` +$plan = New-IdlePlan -WorkflowPath ./workflows/joiner.psd1 -Request $request -Providers $providers +``` + +## PARAMETERS + +### -WorkflowPath +Path to the workflow definition file (PSD1). + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Request +The lifecycle request object created by New-IdleLifecycleRequest. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Providers +Provider registry/collection passed through to planning. +(Structure to be defined later.) + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ProgressAction +{{ Fill ProgressAction Description }} + +```yaml +Type: ActionPreference +Parameter Sets: (All) +Aliases: proga + +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 + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/docs/reference/cmdlets/Test-IdleWorkflow.md b/docs/reference/cmdlets/Test-IdleWorkflow.md new file mode 100644 index 00000000..4ef3f934 --- /dev/null +++ b/docs/reference/cmdlets/Test-IdleWorkflow.md @@ -0,0 +1,88 @@ +--- +external help file: IdLE-help.xml +Module Name: IdLE +online version: +schema: 2.0.0 +--- + +# Test-IdleWorkflow + +## SYNOPSIS +Validates an IdLE workflow definition file. + +## SYNTAX + +``` +Test-IdleWorkflow [-WorkflowPath] [[-Request] ] [-ProgressAction ] + [] +``` + +## DESCRIPTION +Loads and strictly validates a workflow definition (PSD1). +Throws on validation errors. + +## EXAMPLES + +### EXAMPLE 1 +``` +Test-IdleWorkflow -WorkflowPath ./workflows/joiner.psd1 -Request $request +``` + +## PARAMETERS + +### -WorkflowPath +Path to the workflow definition file (PSD1). + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Request +Optional lifecycle request for validating compatibility (LifecycleEvent match). + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ProgressAction +{{ Fill ProgressAction Description }} + +```yaml +Type: ActionPreference +Parameter Sets: (All) +Aliases: proga + +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 + +## OUTPUTS + +### System.Object +## NOTES + +## RELATED LINKS diff --git a/docs/reference/steps.md b/docs/reference/steps.md new file mode 100644 index 00000000..677ba048 --- /dev/null +++ b/docs/reference/steps.md @@ -0,0 +1,66 @@ +# Step Catalog + +> Generated file. Do not edit by hand. +> Source: tools/Generate-IdleStepReference.ps1 + +This page documents built-in IdLE steps discovered from `Invoke-IdleStep*` functions in `IdLE.Steps.*` modules. + +--- + +### EmitEvent + +- **Step Name**: $stepType +- **Implementation**: $commandName +- **Idempotent**: $idempotent +- **Contracts**: $contracts +- **Events**: Unknown + +**Synopsis** + +Emits a custom event (demo step). + +**Description** + +This step does not change external state. It emits a custom event message. +The engine provides an EventSink on the execution context that the step can use +to write structured events. + +**Inputs (With.\*)** + +_Unknown (not detected automatically). Document required With.* keys in the step help and/or use a supported pattern._ + + +--- + +### EnsureAttribute + +- **Step Name**: $stepType +- **Implementation**: $commandName +- **Idempotent**: $idempotent +- **Contracts**: $contracts +- **Events**: Unknown + +**Synopsis** + +Ensures that an identity attribute matches the desired value. + +**Description** + +This is a provider-agnostic step. The host must supply a provider instance via +Context.Providers[]. The provider must implement an EnsureAttribute +method with the signature (IdentityKey, Name, Value) and return an object that +contains a boolean property 'Changed'. + +The step is idempotent by design: it converges state to the desired value. + +**Inputs (With.\*)** + +| Key | Required | +|---|---| +| $k | Yes | +| $k | Yes | +| $k | Yes | + + +--- + diff --git a/tools/Generate-IdleCmdletReference.ps1 b/tools/Generate-IdleCmdletReference.ps1 new file mode 100644 index 00000000..2a463e36 --- /dev/null +++ b/tools/Generate-IdleCmdletReference.ps1 @@ -0,0 +1,257 @@ +[CmdletBinding()] +param( + # Path to the IdLE module manifest to import for documentation generation. + [Parameter()] + [ValidateNotNullOrEmpty()] + [string] $ModuleManifestPath, + + # Output folder for generated cmdlet Markdown files. + # The folder will be created if it does not exist. + [Parameter()] + [ValidateNotNullOrEmpty()] + [string] $OutputFolder, + + # Optional: Create/overwrite an index Markdown file that links all generated cmdlet pages. + [Parameter()] + [ValidateNotNullOrEmpty()] + [string] $IndexPath, + + # Optional: Command names to exclude from generation (exact match). + [Parameter()] + [string[]] $ExcludeCommands = @(), + + # Install platyPS automatically if it is missing (requires internet access). + [Parameter()] + [switch] $InstallPlatyPS +) + +<# +.SYNOPSIS +Generates Markdown reference documentation for IdLE cmdlets using platyPS. + +.DESCRIPTION +This script imports the IdLE module from the current repository clone and then uses the classic +platyPS module (PowerShell Gallery) to generate Markdown reference pages for exported public cmdlets. + +Important: +- This generator intentionally uses ONLY the classic 'platyPS' module and the cmdlet 'New-MarkdownHelp'. +- No fallback to 'Microsoft.PowerShell.PlatyPS' is implemented on purpose to avoid API instability. + +Additionally, it generates an index page (docs/reference/cmdlets.md) that includes a table with cmdlet +links and their synopsis. + +.PARAMETER ModuleManifestPath +Path to the IdLE module manifest (IdLE.psd1). Defaults to ./src/IdLE/IdLE.psd1 relative to this script. + +.PARAMETER OutputFolder +Output folder for the per-cmdlet Markdown files. Defaults to ./docs/reference/cmdlets relative to this script. + +.PARAMETER IndexPath +Path to the index Markdown file. Defaults to ./docs/reference/cmdlets.md relative to this script. + +.PARAMETER ExcludeCommands +Command names to exclude (exact match). Useful if some exported commands are internal or experimental. + +.PARAMETER InstallPlatyPS +If specified, installs platyPS automatically when it is not available. For CI pipelines, you may prefer +pre-installing dependencies and omitting this switch. + +.EXAMPLE +pwsh ./tools/Generate-IdleCmdletReference.ps1 + +.EXAMPLE +pwsh ./tools/Generate-IdleCmdletReference.ps1 -InstallPlatyPS + +.OUTPUTS +System.IO.FileInfo +#> + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +function Resolve-IdleRepoPath { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $Path + ) + + return (Resolve-Path -Path $Path).Path +} + +function Import-IdlePlatyPS { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [switch] $AllowInstall + ) + + $moduleName = 'platyPS' + + if (Get-Module -ListAvailable -Name $moduleName) { + Import-Module -Name $moduleName -ErrorAction Stop | Out-Null + return + } + + if (-not $AllowInstall) { + throw "Required module '$moduleName' is not installed. Install it (PowerShell Gallery) or rerun with -InstallPlatyPS." + } + + if (-not (Get-Command -Name Install-Module -ErrorAction SilentlyContinue)) { + throw "Cannot auto-install '$moduleName' because 'Install-Module' is not available. Install '$moduleName' manually and retry." + } + + Install-Module -Name $moduleName -Scope CurrentUser -Force -AllowClobber -ErrorAction Stop | Out-Null + Import-Module -Name $moduleName -ErrorAction Stop | Out-Null +} + +function Get-IdleCmdletMetadata { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $ModuleName, + + [Parameter()] + [string[]] $Exclude = @() + ) + + $cmds = + Get-Command -Module $ModuleName -CommandType Function, Cmdlet -ErrorAction Stop | + Where-Object { $_.Name -and $_.Name -notin $Exclude } | + Sort-Object -Property Name -Unique + + foreach ($cmd in $cmds) { + $help = $null + try { + $help = Get-Help -Name $cmd.Name -Full -ErrorAction Stop + } + catch { + # Missing help should not fail generation; we reflect it in the synopsis. + } + + $synopsis = '' + if ($null -ne $help -and $help.Synopsis) { + $synopsis = ($help.Synopsis | Out-String).Trim() + } + + if ([string]::IsNullOrWhiteSpace($synopsis)) { + $synopsis = 'No synopsis available (missing comment-based help).' + } + + [pscustomobject]@{ + Name = $cmd.Name + Synopsis = $synopsis + } + } +} + +function New-IdleCmdletIndexMarkdown { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $IndexPath, + + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $OutputFolder, + + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [pscustomobject[]] $Cmdlets + ) + + $indexDir = Split-Path -Path $IndexPath -Parent + if (-not (Test-Path -Path $indexDir)) { + New-Item -Path $indexDir -ItemType Directory -Force | Out-Null + } + + $timestampUtc = [DateTime]::UtcNow.ToString('yyyy-MM-dd HH:mm:ss "UTC"') + + $lines = New-Object System.Collections.Generic.List[string] + $lines.Add('# Cmdlet Reference') + $lines.Add('') + $lines.Add('> Generated file. Do not edit by hand.') + $lines.Add("> Source: tools/Generate-IdleCmdletReference.ps1") + $lines.Add('') + $lines.Add('This page links the generated per-cmdlet reference pages and includes their synopsis.') + $lines.Add('') + + # Table header + $lines.Add('| Cmdlet | Synopsis |') + $lines.Add('| --- | --- |') + + foreach ($cmd in ($Cmdlets | Sort-Object -Property Name)) { + $mdFile = Join-Path -Path $OutputFolder -ChildPath "$($cmd.Name).md" + if (-not (Test-Path -Path $mdFile)) { + continue + } + + # Build a relative link for GitHub rendering. + $relative = [System.IO.Path]::GetRelativePath($indexDir, $mdFile) -replace '\\', '/' + + # Escape table-sensitive characters in synopsis. + $synopsis = ($cmd.Synopsis -replace '\|', '\|').Trim() + + $lines.Add("| [$($cmd.Name)]($relative) | $synopsis |") + } + $lines.Add("") + + Write-Verbose "Writing index file: $IndexPath" + Set-Content -Path $IndexPath -Value ($lines -join "`n") -Encoding utf8 -NoNewline + + $indexFile = Get-Item -Path $IndexPath + Write-Verbose "Index size: $($indexFile.Length) bytes" + + # Emit minimal, stable output (friendly for local runs and CI logs). + "Generated cmdlet reference index: $($indexFile.FullName) ($($indexFile.Length) bytes)" +} + +# Resolve defaults relative to this script to keep usage simple in a repo clone. +$repoRoot = Split-Path -Path $PSScriptRoot -Parent + +if (-not $PSBoundParameters.ContainsKey('ModuleManifestPath')) { + $ModuleManifestPath = Join-Path -Path $repoRoot -ChildPath 'src/IdLE/IdLE.psd1' +} +if (-not $PSBoundParameters.ContainsKey('OutputFolder')) { + $OutputFolder = Join-Path -Path $repoRoot -ChildPath 'docs/reference/cmdlets' +} +if (-not $PSBoundParameters.ContainsKey('IndexPath')) { + $IndexPath = Join-Path -Path $repoRoot -ChildPath 'docs/reference/cmdlets.md' +} + +$ModuleManifestPath = Resolve-IdleRepoPath -Path $ModuleManifestPath + +# Ensure output folder exists. +if (-not (Test-Path -Path $OutputFolder)) { + New-Item -Path $OutputFolder -ItemType Directory -Force | Out-Null +} + +# Load classic platyPS dependency (hard requirement). +Import-IdlePlatyPS -AllowInstall:$InstallPlatyPS + +if (-not (Get-Command -Name 'New-MarkdownHelp' -ErrorAction SilentlyContinue)) { + throw "platyPS is loaded but 'New-MarkdownHelp' is not available. Ensure you installed the classic 'platyPS' module." +} + +# Import IdLE from working tree (deterministic doc generation). +Remove-Module -Name 'IdLE*' -Force -ErrorAction SilentlyContinue +Import-Module -Name $ModuleManifestPath -Force -ErrorAction Stop + +$moduleNameForDocs = 'IdLE' + +# Determine exported commands and synopsis (for index generation). +$cmdletMetadata = @(Get-IdleCmdletMetadata -ModuleName $moduleNameForDocs -Exclude $ExcludeCommands) + +if ($cmdletMetadata.Count -eq 0) { + throw "No exported commands found in module '$moduleNameForDocs'. Ensure the manifest exports public functions." +} + +# Generate per-cmdlet Markdown using classic platyPS. +New-MarkdownHelp -Module $moduleNameForDocs -OutputFolder $OutputFolder -Force | Out-Null +Update-MarkdownHelp -Path $OutputFolder -Force | Out-Null + +# Create/overwrite the index page (table with synopsis). +New-IdleCmdletIndexMarkdown -IndexPath $IndexPath -OutputFolder $OutputFolder -Cmdlets $cmdletMetadata diff --git a/tools/Generate-IdleStepReference.ps1 b/tools/Generate-IdleStepReference.ps1 new file mode 100644 index 00000000..b2517291 --- /dev/null +++ b/tools/Generate-IdleStepReference.ps1 @@ -0,0 +1,344 @@ +[CmdletBinding()] +param( + # Path to the IdLE module manifest to import for documentation generation. + [Parameter()] + [ValidateNotNullOrEmpty()] + [string] $ModuleManifestPath, + + # Markdown output path (will be created/overwritten). + [Parameter()] + [ValidateNotNullOrEmpty()] + [string] $OutputPath, + + # Restrict which step modules are scanned. + [Parameter()] + [ValidateNotNullOrEmpty()] + [string[]] $StepModules = @('IdLE.Steps.Common'), + + # Optional: Step function names to exclude (exact command names). + [Parameter()] + [string[]] $ExcludeCommands = @() +) + +<# +.SYNOPSIS +Generates Markdown reference documentation for IdLE steps. + +.DESCRIPTION +This script imports the IdLE module from the current repository clone and generates a Markdown +"Step Catalog" based on functions following the naming convention: Invoke-IdleStep. + +The generator uses comment-based help (Get-Help) as the primary source and adds a small amount of +heuristic extraction from the step source file (e.g., required With.* keys when they are defined +in a simple static pattern). + +Important: +- Do not edit the generated file by hand. Update step help/source and regenerate. + +.PARAMETER ModuleManifestPath +Path to the IdLE module manifest (IdLE.psd1). Defaults to ./src/IdLE/IdLE.psd1 relative to this script. + +.PARAMETER OutputPath +Path to the generated Markdown file. Defaults to ./docs/reference/steps.md relative to this script. + +.PARAMETER StepModules +Modules that contain step functions (IdLE.Steps.*). + +.PARAMETER ExcludeCommands +Specific step function names to exclude (exact command names). + +.EXAMPLE +pwsh ./tools/Generate-IdleStepReference.ps1 + +.OUTPUTS +System.String +#> + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +function Resolve-IdleRepoPath { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $Path + ) + + return (Resolve-Path -Path $Path).Path +} + +function ConvertTo-IdleMarkdownSafeText { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [AllowEmptyString()] + [string] $Text + ) + + $normalized = $Text -replace "`r`n", "`n" -replace "`r", "`n" + return $normalized.Trim() +} + +function Get-IdleStepTypeFromCommandName { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $CommandName + ) + + $m = [regex]::Match($CommandName, '^Invoke-IdleStep(?.+)$') + if (-not $m.Success) { + return $null + } + + return $m.Groups['Type'].Value +} + +function Get-IdleHelpSafe { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $CommandName + ) + + try { + return Get-Help -Name $CommandName -Full -ErrorAction Stop + } + catch { + return $null + } +} + +function Get-IdleRequiredWithKeysFromSource { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [ValidateNotNull()] + [System.Management.Automation.CommandInfo] $CommandInfo + ) + + # Best-effort heuristic: detect patterns like: + # foreach ($key in @('IdentityKey','Name','Value')) { ... } + $filePath = $null + if ($CommandInfo.ScriptBlock -and $CommandInfo.ScriptBlock.File) { + $filePath = $CommandInfo.ScriptBlock.File + } + + if ([string]::IsNullOrWhiteSpace($filePath) -or -not (Test-Path -Path $filePath)) { + return @() + } + + $content = Get-Content -Path $filePath -Raw -ErrorAction Stop + + $m = [regex]::Match($content, 'foreach\s*\(\s*\$key\s+in\s+@\((?[^)]*)\)\s*\)', 'IgnoreCase') + if (-not $m.Success) { + return @() + } + + $listText = $m.Groups['List'].Value + $keys = [regex]::Matches($listText, "'(?[^']+)'") | ForEach-Object { $_.Groups['Key'].Value } + + return @($keys | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | Select-Object -Unique) +} + +function Get-IdleProviderMethodHintFromDescription { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [AllowEmptyString()] + [string] $DescriptionText + ) + + # Best-effort extraction: + # "must implement an EnsureAttribute method" -> EnsureAttribute + $m = [regex]::Match($DescriptionText, 'must\s+implement\s+an?\s+(?[A-Za-z0-9_]+)\s+method', 'IgnoreCase') + if (-not $m.Success) { + return $null + } + + return $m.Groups['Method'].Value +} + +function ConvertTo-IdleStepMarkdownSection { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [ValidateNotNull()] + [System.Management.Automation.CommandInfo] $CommandInfo + ) + + $commandName = $CommandInfo.Name + $stepType = Get-IdleStepTypeFromCommandName -CommandName $commandName + if ([string]::IsNullOrWhiteSpace($stepType)) { + return $null + } + + $help = Get-IdleHelpSafe -CommandName $commandName + + $synopsis = '' + $description = '' + + if ($null -ne $help) { + if ($help.Synopsis) { + $synopsis = ConvertTo-IdleMarkdownSafeText -Text ($help.Synopsis | Out-String) + } + if ($help.Description -and $help.Description.Text) { + $description = ConvertTo-IdleMarkdownSafeText -Text (($help.Description.Text -join "`n") | Out-String) + } + } + + if ([string]::IsNullOrWhiteSpace($synopsis)) { + $synopsis = 'No synopsis available (missing comment-based help).' + } + + $requiredWithKeys = @(Get-IdleRequiredWithKeysFromSource -CommandInfo $CommandInfo) + $idempotent = 'Unknown' + if ($description -match '(?i)\bidempotent\b') { + $idempotent = 'Yes' + } + + $providerMethod = Get-IdleProviderMethodHintFromDescription -DescriptionText $description + $contracts = if ($providerMethod) { "Provider must implement method: `$providerMethod" } else { 'Unknown' } + + $sb = New-Object System.Text.StringBuilder + + [void]$sb.AppendLine("### $stepType") + [void]$sb.AppendLine() + [void]$sb.AppendLine(("- **Step Name**: `$stepType")) + [void]$sb.AppendLine(("- **Implementation**: `$commandName")) + [void]$sb.AppendLine(("- **Idempotent**: `$idempotent")) + [void]$sb.AppendLine(("- **Contracts**: `$contracts")) + [void]$sb.AppendLine(("- **Events**: Unknown")) + [void]$sb.AppendLine() + [void]$sb.AppendLine("**Synopsis**") + [void]$sb.AppendLine() + [void]$sb.AppendLine($synopsis) + [void]$sb.AppendLine() + + if (-not [string]::IsNullOrWhiteSpace($description)) { + [void]$sb.AppendLine("**Description**") + [void]$sb.AppendLine() + [void]$sb.AppendLine($description) + [void]$sb.AppendLine() + } + + [void]$sb.AppendLine("**Inputs (With.\*)**") + [void]$sb.AppendLine() + + if ($requiredWithKeys.Count -eq 0) { + [void]$sb.AppendLine('_Unknown (not detected automatically). Document required With.* keys in the step help and/or use a supported pattern._') + [void]$sb.AppendLine() + } + else { + [void]$sb.AppendLine('| Key | Required |') + [void]$sb.AppendLine('|---|---|') + foreach ($k in $requiredWithKeys) { + [void]$sb.AppendLine("| `$k` | Yes |") + } + [void]$sb.AppendLine() + } + + return $sb.ToString() +} + +# Resolve defaults relative to this script. +$repoRoot = Split-Path -Path $PSScriptRoot -Parent + +if (-not $PSBoundParameters.ContainsKey('ModuleManifestPath')) { + $ModuleManifestPath = Join-Path -Path $repoRoot -ChildPath 'src/IdLE/IdLE.psd1' +} +if (-not $PSBoundParameters.ContainsKey('OutputPath')) { + $OutputPath = Join-Path -Path $repoRoot -ChildPath 'docs/reference/steps.md' +} + +$ModuleManifestPath = Resolve-IdleRepoPath -Path $ModuleManifestPath + +# Ensure output directory exists. +$outDir = Split-Path -Path $OutputPath -Parent +if (-not (Test-Path -Path $outDir)) { + New-Item -Path $outDir -ItemType Directory -Force | Out-Null +} + +# Import IdLE from working tree. +Remove-Module -Name 'IdLE*' -Force -ErrorAction SilentlyContinue +# Ensure step modules are loaded (Import-Module by name does NOT load nested step modules automatically). +foreach ($m in $StepModules) { + if (Get-Module -Name $m) { + continue + } + + Write-Verbose "Importing step module: $m" + + try { + # Try by module name first (works if it is already discoverable in PSModulePath). + Import-Module -Name $m -Force -ErrorAction Stop + continue + } + catch { + # Fall back to repo-local module path pattern: ./src//.psd1|psm1 + $candidatePsd1 = Join-Path -Path $repoRoot -ChildPath ("src/{0}/{0}.psd1" -f $m) + $candidatePsm1 = Join-Path -Path $repoRoot -ChildPath ("src/{0}/{0}.psm1" -f $m) + + if (Test-Path -Path $candidatePsd1) { + Import-Module -Name $candidatePsd1 -Force -ErrorAction Stop + continue + } + + if (Test-Path -Path $candidatePsm1) { + Import-Module -Name $candidatePsm1 -Force -ErrorAction Stop + continue + } + + throw "Step module '$m' could not be imported. Tried module name and repo paths: '$candidatePsd1', '$candidatePsm1'." + } +} + +# Discover step commands from the configured step modules. +$stepCommands = + foreach ($m in $StepModules) { + Get-Command -Module $m -CommandType Function -ErrorAction SilentlyContinue | + Where-Object { $_.Name -like 'Invoke-IdleStep*' } + } + +$stepCommands = + $stepCommands | + Where-Object { $_.Name -and $_.Name -notin $ExcludeCommands } | + Sort-Object -Property Name -Unique + +if (-not $stepCommands) { + throw "No step commands found. Ensure step modules are included in -StepModules (currently: $($StepModules -join ', '))." +} + +$timestampUtc = [DateTime]::UtcNow.ToString('yyyy-MM-dd HH:mm:ss "UTC"') + +$header = @( + '# Step Catalog' + '' + '> Generated file. Do not edit by hand.' + "> Source: tools/Generate-IdleStepReference.ps1" + '' + 'This page documents built-in IdLE steps discovered from `Invoke-IdleStep*` functions in `IdLE.Steps.*` modules.' + '' + '---' + '' +) -join "`n" + +$body = New-Object System.Text.StringBuilder +[void]$body.AppendLine($header) + +foreach ($cmd in ($stepCommands | Sort-Object)) { + $section = ConvertTo-IdleStepMarkdownSection -CommandInfo $cmd + if (-not [string]::IsNullOrWhiteSpace($section)) { + [void]$body.AppendLine($section) + [void]$body.AppendLine('---') + [void]$body.AppendLine() + } +} + +Set-Content -Path $OutputPath -Value $body.ToString() -Encoding utf8 -NoNewline + +$generatedFile = Get-Item -Path $OutputPath +"Generated step reference: $($generatedFile.FullName) ($($generatedFile.Length) bytes)"