documentarian.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
[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 *