ArchitectureDecisionRecords.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
<#
.Synopsis
Gets the directory ADRs are stored in for this project.
 
.Description
Gets the directory ADRS are stored in for this project. Directory is relative
to the correct working dir.
 
Supports an ADR_DIR environment variable or a .adr-dir file specifying the path.
If both are provided, an error will be thrown. If neither is provided, the default
doc/adr directory will be used.
#>

Function Get-AdrDir {
  [CmdletBinding()]
  [OutputType([string])]
  Param()

  if ($env:ADR_DIR -and (Test-Path '.adr-dir')) {
    throw 'Cannot use both the .adr-dir file and ADR_DIR env var.'
  } elseif ($env:ADR_DIR) {
    $env:ADR_DIR
  } elseif (Test-Path '.adr-dir') {
    Get-Content '.adr-dir'
  } else {
    'doc/adr'
  }
}

<#
.Synopsis
Gets a Markdown template to use for ADRs.
 
.Description
Get a Markdown template for use by ADRs, from one of many sources.
 
- Path parameter on this function
- ADR_TEMPLATE environment variable
- $(Get-AdrDir)/templates/template.md
- A template included in this module
 
.Parameter Path
Path to the template to use over the other auto-lookup sources.
#>

Function Get-AdrTemplate {
  [CmdletBinding()]
  [OutputType([string])]
  Param(
    [Parameter()]
    [string] $Path
  )

  $DstDir = Get-AdrDir
  $CustomTemplateFile = Join-Path -Path $DstDir -ChildPath 'templates/template.md'
  if ($Path) {
    if (-not (Test-Path -Path $Path)) {
      throw "Specified template path does not exist: $Path"
    }
    $TemplateFile = $Path
  } elseif ($env:ADR_TEMPLATE) {
    if (-not (Test-Path -Path $env:ADR_TEMPLATE)) {
      throw "Specified ADR_TEMPLATE does not exist: $($env:ADR_TEMPLATE)"
    }
    $TemplateFile = $env:ADR_TEMPLATE
  } elseif (Test-Path $CustomTemplateFile) {
    $TemplateFile = $CustomTemplateFile
  } else {
    $TemplateFile = Join-Path -Path $MyInvocation.MyCommand.Module.ModuleBase -ChildPath 'template.md'
  }
  Get-Content -Path $TemplateFile -Encoding UTF8NoBOM
}

<#
.Synopsis
Converts an ADR object into ADR markdown.
 
.Description
Converts an ADR object into ADR markdown via a template. The template will be
sourced from one of the following locations:
 
- Template parameter on this function
- ADR_TEMPLATE environment variable
- $(Get-AdrDir)/templates/template.md
- A template included in this module
 
.Parameter InputObject
A custom object representing the state of the ADR to be rendered.
 
.Parameter Tempalte
Path to the template to use over the other auto-lookup sources.
#>

Function ConvertTo-AdrText {
  [CmdletBinding()]
  [OutputType([String])]
  Param(
    [Parameter(Mandatory = $True, ValueFromPipeline = $True)]
    [PSCustomObject] $InputObject,

    [Parameter()]
    [string] $Template
  )

  Begin {
    $TemplateContent = Get-AdrTemplate -Path:$Template
  }
  Process {
    $Replacements = @{
      'NUMBER'       = $InputObject.Number;
      'TITLE'        = $InputObject.Title;
      'DATE'         = $InputObject.Date;
      'STATUS'       = $InputObject.Status;
      'CONTEXT'      = $InputObject.Context;
      'DECISION'     = $InputObject.Decision;
      'CONSEQUENCES' = $InputObject.Consequences;
    }
    $Content = $TemplateContent
    ForEach ($Replacement in $Replacements.GetEnumerator()) {
      $Content = $Content -creplace $Replacement.Name, $Replacement.Value
    }
    $Content
  }
}

<#
.Synopsis
Converts ADR markdown text into an ADR object.
 
.Description
Converts ADR markdown text into an ADR object.
 
.Parameter InputObject
A string of Markdown text to convert into an ADR object.
#>

Function ConvertFrom-AdrText {
  [CmdletBinding()]
  [OutputType([PSCustomObject])]
  Param(
    [Parameter(Mandatory = $True, ValueFromPipeline = $True)]
    [string] $InputObject
  )

  Process {
    # Find title
    if ($InputObject -match '# (\d+)\. (.+)(?:`n|\s)+Date: (.+)') {
      $Number = [int]$Matches[1]
      $Title = $Matches[2].Trim()
      $Date = $Matches[3].Trim()
    }

    # Find status
    if ($InputObject -match '(?s)## Status(.*?)(?:##|$)') {
      $Status = $Matches[1].Trim()
    }

    # Find context
    if ($InputObject -match '(?s)## Context(.*?)(?:##|$)') {
      $Context = $Matches[1].Trim()
    }

    # Find decision
    if ($InputObject -match '(?s)## Decision(.*?)(?:##|$)') {
      $Decision = $Matches[1].Trim()
    }

    # Find consequences
    if ($InputObject -match '(?s)## Consequences(.*?)(?:##|$)') {
      $Consequences = $Matches[1].Trim()
    }

    [PSCustomObject]@{
      'Number'       = $Number;
      'Title'        = $Title;
      'Date'         = $Date;
      'Status'       = $Status;
      'Context'      = $Context;
      'Decision'     = $Decision;
      'Consequences' = $Consequences;
    }
  }
}

<#
.Synopsis
Initializes an ADR directory.
 
.Description
Initliazes an ADR directory and populates it with an initial decision to use ADRs.
 
.Parameter Target
If provided, creates an .adr-dir file with the target path as it's content, creates
the target path as a directory (if it doesn't already exist) and uses this as the
directory to populate the initial decision. If omitted, uses doc/adr as the target.
#>

Function Initialize-Adr {
  [CmdletBinding()]
  Param(
    [Parameter()]
    [string] $Target
  )

  if ($Target) {
    # If target provided, create .adir-dir file to point to it
    Set-Content -Path '.adr-dir' -Value "$($Target)" -Encoding UTF8NoBOM
  }

  $TemplateFile = Join-Path -Path $MyInvocation.MyCommand.Module.ModuleBase -ChildPath 'init.md'
  New-Adr -Title 'Record architecture decisions' -Status 'Accepted' -Template $TemplateFile
}

<#
.Synopsis
Gets all ADRs or a single ADR from the ADR dir.
 
.Description
Gets all ADRs from the ADR dir, parsed as objects. If a number is specified, only that
ADR will be returned.
 
.Parameter Number
Get a single ADR with the number given. If not specified, all ADRs will be returned.
#>

Function Get-Adr {
  [CmdletBinding()]
  [OutputType([PSCustomObject[]])]
  Param(
    [Parameter()]
    [int] $Number
  )

  $Dir = Get-AdrDir

  if (-not (Test-Path $Dir)) {
    Write-Error "ADR dir does not exist: $Dir"
    return @()
  }

  $AdrFiles = Get-ChildItem -Path $Dir -Filter '*.md' |
    Where-Object { $_.Name -match '(\d+)-.+\.md' } |
    Where-Object { ($Number -eq 0) -or ($Number -eq [int]$Matches[1]) }

  $AdrFiles | ForEach-Object {
    $Result = ConvertFrom-AdrText -InputObject (Get-Content -Path $_.FullName -Encoding UTF8NoBOM -Raw)
    Add-Member -InputObject $Result -MemberType NoteProperty -Name 'Path' -Value $_.FullName
    $Result
  }
}

<#
.Synopsis
Adds an link between two ADRs.
 
.Description
Adds a link between two ADRs, optionally with a reverse link.
 
.Parameter FromNumber
The number of the ADR to link from.
 
.Parameter FromLink
The text to prefix the forward link with.
 
.Parameter ToNumber
The number of the ADR to link to.
 
.Parameter ToLink
The text to prefix the reverse link with. If not specified the To ADR will not be modified.
 
.Example
Add-AdrLink -FromNumber 1 -ToNumber 2 -FromLink "Linked" -ToLink "Linked"
 
.Example
Add-AdrLink -FromNumber 1 -ToNumber 2 -FromLink "Superseded by" -ToLink "Supersedes"
#>

Function Add-AdrLink {
  [CmdletBinding()]
  Param(
    [Parameter(Mandatory = $True)]
    [int] $FromNumber,

    [Parameter(Mandatory = $True)]
    [string] $FromLink,

    [Parameter(Mandatory = $True)]
    [int] $ToNumber,

    [Parameter()]
    [string] $ToLink
  )

  if ($FromNumber -eq $ToNumber -or $FromNumber -le 0 -or $ToNumber -le 0) {
    throw 'FromNumber and ToNumber must be different and greater than 0'
  }

  $FromAdr = Get-Adr -Number $FromNumber
  $ToAdr = Get-Adr -Number $ToNumber

  if ($FromAdr -and $ToAdr) {
    $ToFile = Split-Path -Path $ToAdr.Path -Leaf

    $FromAdr.Status = @"
$($FromAdr.Status)
 
$FromLink [$($ToAdr.Title)]($ToFile)
"@
.Trim()

    $Content = ConvertTo-AdrText -InputObject $FromAdr
    Set-Content -Path $FromAdr.Path -Value $Content -Encoding UTF8NoBOM

    if ($ToLink) {
      Add-AdrLink -FromNumber $ToNumber -FromLink $ToLink -ToNumber $FromNumber
    }
  } else {
    Write-Error "Both ADR number $FromNumber and $ToNumber must exist."
  }
}

<#
.Synopsis
Removes the status in the given ADR.
 
.Description
Removes the status in the given ADR.
 
.Parameter Number
The number of the ADR to remove the status of.
#>

Function Remove-AdrStatus {
  [CmdletBinding()]
  [OutputType([hashtable[]])]
  Param(
    [Parameter(Mandatory = $True)]
    [int] $Number
  )

  if ($Number -le 0) {
    throw 'Invalid ADR number. Must be a positive integer'
  }

  $Adr = Get-Adr -Number $Number
  if ($Adr) {
    $Adr.Status = ''
    $Content = ConvertTo-AdrText -InputObject $Adr
    Set-Content -Path $Adr.Path -Value $Content -Encoding UTF8NoBOM
  } else {
    Write-Error "No ADR found for number: $Number"
  }
}

<#
.Synopsis
Create a new ADR.
 
.Description
Creates a new ADR numbered after the ADRs currently present in the ADR dir.
 
.Parameter Title
The title of the ADR.
 
.Parameter Status
The initial status of the ADR. Can be Proposed or Accepted (default).
 
.Parameter Supersede
An array of ADR numbers that are superseded by this ADR.
 
.Parameter Link
An array of link specs to add from this ADR. A link spec is as follows:
 
<ToNumber>:<ToLink>:<FromLink>
 
Example: '8:Amends:Amended by'
 
.Parameter Template
Path to the template to use over the other auto-lookup sources. This is meant for internal use only.
#>

Function New-Adr {
  [CmdletBinding()]
  Param(
    [Parameter(Mandatory = $True)]
    [string] $Title,

    [ValidateSet('Proposed', 'Accepted')]
    [Parameter()]
    [string] $Status = 'Accepted',

    [Parameter()]
    [int[]] $Supersede,

    [ValidatePattern('^\d+\:[\w -]+\:[\w -]+$')]
    [Parameter()]
    [string[]] $Link,

    [Parameter()]
    [string] $Template
  )

  $DstDir = Get-AdrDir
  $MaxAdrNum = [int](Get-Adr -ErrorAction SilentlyContinue | Select-Object -ExpandProperty 'Number' | Measure-Object -Maximum).Maximum
  $NewNum = $MaxAdrNum + 1

  # Remove any leading/trailing non-alphanumeric characters. Intermediate non-alphanumeric replaced by a dash
  $Slug = ($Title.ToLower() -replace '^[^a-z0-9]+|[^a-z0-9]+$', '') -replace '[^a-z0-9]+', '-'

  $FileName = '{0:d4}-{1}.md' -f $NewNum, $Slug
  $DstFile = Join-Path -Path $DstDir -ChildPath $FileName

  $Date = Get-Date -Format 'yyyy-MM-dd'

  $Adr = @{'Number' = $NewNum; 'Title' = $Title; 'Date' = $Date; 'Status' = $Status}
  $Content = ConvertTo-AdrText -InputObject $Adr -Template:$Template
  New-Item -ItemType Directory -Path $DstDir -Force | Out-Null
  Set-Content -Path $DstFile -Value $Content -Encoding UTF8NoBOM

  ForEach ($SupersedeNum in $Supersede) {
    Remove-AdrStatus -Number $SupersedeNum
    Add-AdrLink -FromNumber $NewNum -FromLink 'Supersedes' -ToNumber $SupersedeNum -ToLink 'Superseded by'
  }

  ForEach ($LinkSpec in $Link) {
    $ToNumber, $FromLink, $ToLink = $LinkSpec -split '\:'
    Add-AdrLink -FromNumber $NewNum -FromLink $FromLink -ToNumber $ToNumber -ToLink $ToLink
  }
}

<#
.Synopsis
Generates an ADR TOC in the ADR dir's README.md file.
 
.Description
Generates a table of contents of the ADRs in ADR dir and outputs
it into a README.md file as a sibling to the ADRs.
#>

Function Reset-AdrToc {
  [CmdletBinding()]
  Param()

  $Links = (Get-Adr | ForEach-Object { "- [$($_.Title)]($($LinkPrefix)$(Split-Path $_.Path -Leaf))" }) -join "`r`n"

  $Content = @"
# Architecture Decision Records
 
## Decisions
 
$Links
"@


  $Path = Join-Path -Path (Get-AdrDir) -ChildPath 'README.md'
  Set-Content -Path $Path -Value $Content -Encoding UTF8NoBOM
}