documentarian.psm1

[string]$GitBookPlasterTemplate = Resolve-Path -Path "$PSScriptRoot/gitbook"
function Resolve-GitBookConfigurationFilePath {
    [CmdletBinding()]
    param (
        [string]$ConfigurationFilePath
    )
    
    begin {
    }
    
    process {
        If ([string]::IsNullOrEmpty($ConfigurationFilePath)) {
            $DiscoveredConfigurationFiles = Resolve-Path './docs/book.json','./book.json' -ErrorAction SilentlyContinue
            If ($DiscoveredConfigurationFiles.Count -eq 0) {
                $NoConfigurationFileFoundMessage = @(
                    "No GitBook configuration file (book.json) specified, no configuration file found in default paths:"
                    " ./docs/book.json"
                    " ./book.json"
                    "Please specify the path to a valid gitbook configuration file."
                ) -join "`r`n"
                Throw $NoConfigurationFileFoundMessage
            } ElseIf ($DiscoveredConfigurationFiles.Count -gt 1) {
                $AmbiguousConfigurationFileMessage = @(
                    "No GitBook configuration file (book.json) specified, configuration files found in both default paths:"
                    " ./docs/book.json"
                    " ./book.json"
                    "Please specify one configuration file to update."
                ) -join "`r`n"
                Throw $AmbiguousConfigurationFileMessage
            } Else {
                [string]$DiscoveredConfigurationFiles
            }
        } Else {
            Try {
                [string](Resolve-Path -Path $ConfigurationFilePath -ErrorAction Stop)
            } Catch {
                Throw $PSItem.Exception
            }
        }
    }
    
    end {
    }
}
function Add-GitBookPlugin {
  <#
    .SYNOPSIS
    Add a gitbook plugin to the project's documentation config
    .DESCRIPTION
    Add a gitbook plugin to the project's documentation configuration.
    You can specify a '-' at the beginning of the plugin name to remove a built-in plugin.
    .PARAMETER PluginName
    The name(s) of the plugin(s) to be added to the config file.
    This function does not verify whether or not the plugin is valid or discoverable.
    
    If you specify a '-' at the beginning of the plugin name for a default plugin it will instead remove that plugin from the load order.
    This only works for built-in plugins.

    Note that this command does _not_ modify the pluginConfig setting where individual plugins are configured.
    It adds the plugin to the load list and will therefore get the plugin's default config.
    .PARAMETER ConfigurationFilePath
    The path to the GitBook configuration file.
    Will search for the file in the default locations if not specified.
    .EXAMPLE
    Add-GitBookPlugin -PluginName code
    Adds the code plugin to the default GitBook config in the project.
    .EXAMPLE
    'code', 'code-captions' | Add-GitBookPlugin
    Adds the code and code-captions plugins to the default GitBook config in the project, showing passing plugins by the pipeline.
    .EXAMPLE
    Add-GitBookPlugin -PluginName code -ConfigurationFilePath ./example/book.json
    .INPUTS
    String[]
    One or more strings representing the plugins to be added.
    .OUTPUTS
    String
    JSON string representation of the GitBook config after updating.
    .NOTES
    Alias: agbp
  #>

  [CmdletBinding()]
  param (
    [Alias('Name','Plugin')]
    [Parameter(ValueFromPipeline=$true)]
    [string[]]$PluginName,
    [Alias('Path','FilePath','Config')]
    [string]$ConfigurationFilePath
  )
  
  begin {
    If ([string]::IsNullOrEmpty($ConfigurationFilePath)) {
      $ConfigurationFilePath = Resolve-GitBookConfigurationFilePath
    } Else {
      $ConfigurationFilePath = Resolve-GitBookConfigurationFilePath -ConfigurationFilePath $ConfigurationFilePath
    }
    $Configuration = Get-Content $ConfigurationFilePath -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
  }
  
  process {
    ForEach ($Plugin in $PluginName) {
      If ($Plugin -notin $Configuration.Plugins) {
        $Configuration.Plugins += $Plugin
      } Else {
        Write-Warning "GitBook Plugin [$Plugin] already found in configuration"
      }
    }
  }
  
  end {
    $Configuration | ConvertTo-Json -OutVariable ConfigurationJson | Out-File $ConfigurationFilePath
    $ConfigurationJson
  }
}

Set-Alias -Name agbp -Value Add-GitBookPlugin
function New-Document {
  
  <#
    .SYNOPSIS
    Create new markdown docs in the docs folder.
    
    .DESCRIPTION
    Scaffold new markdown documents in the project with headers and subchapters.

    .PARAMETER Title
    The title of the document to be created.
    Optionally, you can specify the title to include both the type and chapters, such as 'Concept/Chapter/Subchapter/My Document Title'

    .PARAMETER Type
    The type of documentation to be created, usually concept, narrative, or reference.
    Determines which folder inside the docs directory to place the subchapters and document.

    .PARAMETER Chapter
    Arbitrary subchapters for the document to reside within, separated by a forward slash.
    
    .EXAMPLE
    New-Document -Type Narrative -Title "Using Helper Functions" -Chapter "Workflow"

    This example shows the most explicit use of the command to create a markdown document at `./docs/narrative/Workflow/using-helper-functions.md`

    .EXAMPLE
    New-Document -Type Concept -Title "Writing Helper Functions" -Chapter "Contributing/Code"

    This example shows using the command to create a markdown document in subchapters at `./docs/concept/Contributing/Code/writing-helper-functions.md`

    .EXAMPLE
    New-Document -Title "Concept/Contributing/Code/Writing Helper Functions"

    In this example we use the shorthand specification in the title, including the type of documentation and chapters prepended to the title.

    .EXAMPLE
    'Concept/Contributing/Code/Writing Helper Functions','Narrative/Workflow/Using Helper Functions" `
    | New-Document

    Here we show that you can pass multiple titles in the shorthand format to the command over the pipeline.

  #>


  [CmdletBinding()]
  param (
    [Parameter(Position=0, ValueFromPipeline=$true)]
    [string]$Title,
    [string]$Type,
    [string]$Chapter
  )
  
  begin {
    If (!(Test-Path ./docs)) {
      Throw "Could not find docs folder; command must be run from root of project with a docs folder."
    }
  }
  
  process {
    # Determine whether or not to parse the title for the type and chapter:
    $TypeNotSpecified    = $Type    -in    @($null, "")
    $ChapterNotSpecified = $Chapter -in    @($null, "")
    $TitleIncludesType   = $Title   -match '^\w+/'
    If ($TitleIncludesType -and $TypeNotSpecified -and $ChapterNotSpecified) {
      # If correctly formatted, title can then be split to retrieve from Type/Chapter/Title
      $SplitTitle = $Title.Split('/')
      $Type       = $SplitTitle[0]
      $Title      = $SplitTitle[-1]
      # Chapters aren't necessary, so if they're not included, don't make a goofy layout.
      If ($SplitTitle.Count -gt 2) {
        $Chapter    = $SplitTitle[1..($SplitTitle.Count - 2)] -join '/'
      } Else {
        $Chapter = ""
      }
    }

    $DocumentFolder = "./docs/$Type/$Chapter"
    $DocumentName   = $Title.Replace(' ','-').ToLower()
    $DocumentPath   = "$DocumentFolder/$DocumentName.md"
    If (!(Test-Path $DocumentFolder)) {
      New-Item -Path $DocumentFolder -ItemType Directory -Force | Out-Null
    }
    If (!(Test-Path -Path $DocumentPath)) {
      New-Item -Path $DocumentPath -ItemType File -Value "# $Title"
    }

    # Cleanup Type and Chapter for pipeline
    $Type    = ""
    $Chapter = ""
  }
  
  end {
  }
}
function Remove-GitBookPlugin {
  <#
    .SYNOPSIS
      Remove a gitbook plugin to the project's documentation config
    .DESCRIPTION
      Remove a gitbook plugin to the project's documentation configuration.
    .PARAMETER PluginName
      The name(s) of the plugin(s) to be removed from the config file.
      This function does not verify whether or not the plugin is valid or discoverable.

      Note that this command _does_ modify the pluginConfig setting where individual plugins are configured.
      It removes the plugin to the load list and from the pluginConfig both.
    .PARAMETER ConfigurationFilePath
      The path to the GitBook configuration file.
      Will search for the file in the default locations if not specified.
    .EXAMPLE
      Remove-GitBookPlugin -PluginName code
      Removes the code plugin from the default GitBook config in the project.
    .EXAMPLE
      'code', 'code-captions' | Remove-GitBookPlugin
      Removes the code and code-captions plugins from the default GitBook config in the project, showing passing plugins by the pipeline.
    .EXAMPLE
      Remove-GitBookPlugin -PluginName code -ConfigurationFilePath ./example/book.json
    .INPUTS
      String{}
      One or more strings representing the plugins to be removed.
    .OUTPUTS
      String
      JSON string representation of the GitBook config after updating.
    .NOTES
      Alias: rgbp
  #>

  [CmdletBinding()]
  param (
    [Alias('Name','Plugin')]
    [Parameter(ValueFromPipeline=$true)]
    [string[]]$PluginName,
    [Alias('Path','FilePath','Config')]
    [string]$ConfigurationFilePath
  )
  
  begin {
    If ([string]::IsNullOrEmpty($ConfigurationFilePath)) {
      $ConfigurationFilePath = Resolve-GitBookConfigurationFilePath
    } Else {
      $ConfigurationFilePath = Resolve-GitBookConfigurationFilePath -ConfigurationFilePath $ConfigurationFilePath
    }
    $Configuration = Get-Content $ConfigurationFilePath -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
  }
  
  process {
    ForEach ($Plugin in $PluginName) {
      If ($Plugin -in $Configuration.Plugins) {
        $Configuration.Plugins = $Configuration.Plugins | Where-Object -FilterScript {$PSItem -ne $Plugin}
        # Because the config is returned as a PSCustomObject we need to use PSObject.Properties
        # instead of recursing through the hash and removing the key. This works roughly the same.
        If ($Configuration.PluginsConfig.PSObject.Properties.Name -contains $Plugin) {
          $Configuration.PluginsConfig.PSObject.Properties.Remove($Plugin)
        }
      } Else {
        Write-Warning "GitBook Plugin [$Plugin] not found in configuration"
      }
    }
  }
  
  end {
    $Configuration | ConvertTo-Json -OutVariable ConfigurationJson | Out-File $ConfigurationFilePath
    $ConfigurationJson
  }
}

Set-Alias -Name rgbp -Value Remove-GitBookPlugin
Export-ModuleMember -Variable * -Function * -Alias *