Types/OpenPackage.Publisher/Markdown.ps1

<#
.SYNOPSIS
    Publishes Markdown
.DESCRIPTION
    Publishes Markdown within a package as a static site.
.NOTES
    This formats all markdown in the package,
    and exports each markdown file into an index.html.

    If the markdown file was named README,
    will try to place an index in the same directory.
#>

[CmdletBinding(PositionalBinding=$false,SupportsShouldProcess)]
param(
# The destination path of the website.
[Parameter(Position=0)]
[string]
$DestinationPath = './_site',

# Any input object. This should be one or more packages.
# If no input is provided, will archive the current directory and publish a page.
[Parameter(ValueFromPipeline)]
[Alias('Package')]
[PSObject[]]
$InputObject
)

# Quickly enumerate all input and arguments.
$allInput = @($input)
if (-not $allInput -and $InputObject) {
    $allInput += $InputObject
}

# If there is no input
if (-not $allInput) {
    # exclude our destination from the input
    $excludeWildCard = $DestinationPath -replace './', '*' -replace '$', '*'
    # and make a package from the current directory.
    $allInput = @(Get-OpenPackage -FilePath . -Exclude $excludeWildCard)
}

# Still no input? Return.
if (-not $allInput) { return }

# Next up, we can take any markdown in the package and make it an index.html
$allInput | 
    # First up, format it as markdown.
    # This will apply styles and frame the content.
    Format-OpenPackage -View Markdown.html |
    Foreach-Object {
        $md = $_
        $markdownHtmlPath = 
            if ($md.PartUri -match '/index\.(?>md|markdown)$') {
                Join-Path $DestinationPath (
                    $md.PartUri -replace '\.(?>md|markdown)$', '.html'
                )
            } 
            elseif ($md.PartUri -match '/README\.(?>md|markdown)$') {
                Join-Path $DestinationPath (
                    $md.PartUri -replace '/README\.(?>md|markdown)$', '/index.html'
                )
            }
            elseif ($md.PartUri) {
                Join-Path $DestinationPath (
                    $md.PartUri -replace '\.(?>md|markdown)$', '/index.html'
                )
            }

        if (-not $markdownHtmlPath) {
            continue
        }
        
        New-Item -ItemType File -Value "$md" -Path $markdownHtmlPath -Force
    }