-
Notifications
You must be signed in to change notification settings - Fork 40
/
docs.go
1727 lines (1487 loc) · 57.1 KB
/
docs.go
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016-2018, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tfgen
import (
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strings"
"sync"
"github.com/hashicorp/go-multierror"
"golang.org/x/text/cases"
"golang.org/x/text/language"
"github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tf2pulumi/gen/python"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
"github.com/spf13/afero"
"github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tf2pulumi/convert"
"github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfbridge"
)
// argumentDocs contains the documentation metadata for an argument of the resource.
type argumentDocs struct {
// The description for this argument.
description string
// (Optional) The names and descriptions for each argument of this argument.
arguments map[string]string
// Whether this argument was derived from a nested object. Used to determine
// whether to append descriptions that have continued to the following line
isNested bool
}
// Included for testing convenience.
func (ad argumentDocs) MarshalJSON() ([]byte, error) {
j, err := json.Marshal(struct {
Description string
Arguments map[string]string
IsNested bool
}{
Description: ad.description,
Arguments: ad.arguments,
IsNested: ad.isNested,
})
if err != nil {
return nil, err
}
return j, nil
}
// entityDocs represents the documentation for a resource or datasource as extracted from TF markdown.
type entityDocs struct {
// Description is the description of the resource
Description string
// Arguments maps the name of each argument of the resource to its metadata.
// Each argument has a description. Some arguments have their own arguments.
//
// For example, using a couple arguments from s3_bucket.html.markdown, we
// expect to see a map like this, where "bucket" and "website" are top-level
// arguments, and "index_document" is an argument of "website":
// - bucket
// - description: "(Optional, Forces new resource) The name of the bucket.
// If omitted, Terraform will assign a random, unique name."
// - website
// - description: "(Optional) A website object (documented below)."
// - arguments:
// - index_document: "(Required, unless using `redirect_all_requests_to`)
// Amazon S3 returns this index document when requests are made to the
// root domain or any of the subfolders."
// - index_document
// - description: "(Required, unless using `redirect_all_requests_to`)
// Amazon S3 returns this index document when requests are made to the
// root domain or any of the subfolders."
// - isNested: true
// "index_document" is recorded like a top level argument since sometimes object names in
// the TF markdown are inconsistent. For example, see `cors_rule` in s3_bucket.html.markdown.
Arguments map[string]*argumentDocs
// Attributes includes the names and descriptions for each attribute of the resource
Attributes map[string]string
// Import is the import details for the resource
Import string
}
func (ed *entityDocs) getOrCreateArgumentDocs(argumentName string) (*argumentDocs, bool) {
if ed.Arguments == nil {
ed.Arguments = make(map[string]*argumentDocs)
}
var created bool
args, has := ed.Arguments[argumentName]
if !has {
args = &argumentDocs{arguments: make(map[string]string)}
ed.Arguments[argumentName] = args
created = true
}
return args, created
}
// DocKind indicates what kind of entity's documentation is being requested.
type DocKind string
const (
// ResourceDocs indicates documentation pertaining to resource entities.
ResourceDocs DocKind = "resources"
// DataSourceDocs indicates documentation pertaining to data source entities.
DataSourceDocs DocKind = "data-sources"
)
var repoPaths sync.Map
func getRepoPath(gitHost string, org string, provider string, version string) (string, error) {
moduleCoordinates := fmt.Sprintf("%s/%s/terraform-provider-%s", gitHost, org, provider)
if version != "" {
moduleCoordinates = fmt.Sprintf("%s/%s", moduleCoordinates, version)
}
if path, ok := repoPaths.Load(moduleCoordinates); ok {
return path.(string), nil
}
curWd, err := os.Getwd()
if err != nil {
return "", fmt.Errorf("error finding current working directory: %w", err)
}
if filepath.Base(curWd) != "provider" {
curWd = filepath.Join(curWd, "provider")
}
command := exec.Command("go", "mod", "download", "-json", moduleCoordinates)
command.Dir = curWd
output, err := command.CombinedOutput()
if err != nil {
return "", fmt.Errorf("error running 'go mod download -json' for module: %w", err)
}
target := struct {
Version string
Dir string
Error string
}{}
if err := json.Unmarshal(output, &target); err != nil {
return "", fmt.Errorf("error parsing output of 'go mod download -json' for module: %w", err)
}
if target.Error != "" {
return "", fmt.Errorf("error from 'go mod download -json' for module: %s", target.Error)
}
repoPaths.Store(moduleCoordinates, target.Dir)
return target.Dir, nil
}
func getMarkdownDetails(org string, provider string, resourcePrefix string, kind DocKind, rawname string,
info tfbridge.ResourceOrDataSourceInfo, providerModuleVersion string, githost string) ([]byte, string, bool) {
var docinfo *tfbridge.DocInfo
if info != nil {
docinfo = info.GetDocs()
}
if docinfo != nil && len(docinfo.Markdown) != 0 {
return docinfo.Markdown, "", true
}
repoPath, err := getRepoPath(githost, org, provider, providerModuleVersion)
if err != nil {
return nil, "", false
}
possibleMarkdownNames := []string{
// Most frequently, docs leave off the provider prefix
withoutPackageName(resourcePrefix, rawname) + ".html.markdown",
withoutPackageName(resourcePrefix, rawname) + ".markdown",
withoutPackageName(resourcePrefix, rawname) + ".html.md",
withoutPackageName(resourcePrefix, rawname) + ".md",
// But for some providers, the prefix is included in the name of the doc file
rawname + ".html.markdown",
rawname + ".markdown",
rawname + ".html.md",
rawname + ".md",
}
if docinfo != nil && docinfo.Source != "" {
possibleMarkdownNames = append(possibleMarkdownNames, docinfo.Source)
}
markdownBytes, markdownFileName, found := readMarkdown(repoPath, kind, possibleMarkdownNames)
if !found {
return nil, "", false
}
return markdownBytes, markdownFileName, true
}
func (k DocKind) String() string {
switch k {
case DataSourceDocs:
return "data source"
case ResourceDocs:
return "resource"
default:
return ""
}
}
// formatEntityName checks for an aliases TF entity name (ending with "_legacy") and returns it formatted for end user
// consumption in log messages, etc. Without this conversion, users who do not have direct knowledge of how
// aliased/renamed entities will be confused by the implicit renaming because the "_legacy" resource mapping does not
// appear in the provider mapping, nor the upstream provider source.
func formatEntityName(rawname string) string {
if strings.Contains(rawname, tfbridge.RenamedEntitySuffix) {
return fmt.Sprintf("'%s' (aliased or renamed)", strings.Replace(rawname, tfbridge.RenamedEntitySuffix, "", -1))
}
return fmt.Sprintf("'%s'", rawname)
}
// getDocsForProvider extracts documentation details for the given package from
// TF website documentation markdown content
func getDocsForProvider(g *Generator, org string, provider string, resourcePrefix string, kind DocKind,
rawname string, info tfbridge.ResourceOrDataSourceInfo, providerModuleVersion string,
githost string) (entityDocs, error) {
if g.skipDocs {
return entityDocs{}, nil
}
markdownBytes, markdownFileName, found := getMarkdownDetails(org, provider, resourcePrefix, kind, rawname, info,
providerModuleVersion, githost)
if !found {
entitiesMissingDocs++
msg := fmt.Sprintf("could not find docs for %v %v. Override the Docs property in the %v mapping. See "+
"type tfbridge.DocInfo for details.", kind, formatEntityName(rawname), kind)
if isTruthy(os.Getenv("PULUMI_MISSING_DOCS_ERROR")) {
g.error(msg)
return entityDocs{}, fmt.Errorf(msg)
}
// Ideally, we would still want to still return an error here and let upstream callers handle it, but at the
// time the option to fail the build for missing docs was added (see just above), there are multiple callers of
// this function who do not expect docs not being found to return an error, and the cost of doing the idiomatic
// thing (returning an error) was too high.
g.warn(msg)
return entityDocs{}, nil
}
doc, err := parseTFMarkdown(g, info, kind, string(markdownBytes), markdownFileName, resourcePrefix, rawname)
if err != nil {
return entityDocs{}, err
}
var docinfo *tfbridge.DocInfo
if info != nil {
docinfo = info.GetDocs()
}
if docinfo != nil {
// Helper func for readability due to large number of params
getSourceDocs := func(sourceFrom string) (entityDocs, error) {
return getDocsForProvider(g, org, provider, resourcePrefix, kind, sourceFrom, nil, providerModuleVersion, githost)
}
if docinfo.IncludeAttributesFrom != "" {
sourceDocs, err := getSourceDocs(docinfo.IncludeAttributesFrom)
if err != nil {
return doc, err
}
overlayAttributesToAttributes(sourceDocs, doc)
}
if docinfo.IncludeAttributesFromArguments != "" {
sourceDocs, err := getSourceDocs(docinfo.IncludeAttributesFromArguments)
if err != nil {
return doc, err
}
overlayArgsToAttributes(sourceDocs, doc)
}
if docinfo.IncludeArgumentsFrom != "" {
sourceDocs, err := getSourceDocs(docinfo.IncludeArgumentsFrom)
if err != nil {
return doc, err
}
overlayArgsToArgs(sourceDocs, doc)
}
}
return doc, nil
}
func overlayAttributesToAttributes(sourceDocs entityDocs, targetDocs entityDocs) {
for k, v := range sourceDocs.Attributes {
targetDocs.Attributes[k] = v
}
}
func overlayArgsToAttributes(sourceDocs entityDocs, targetDocs entityDocs) {
for k, v := range sourceDocs.Arguments {
targetDocs.Attributes[k] = v.description
for kk, vv := range v.arguments {
targetDocs.Attributes[kk] = vv
}
}
}
func overlayArgsToArgs(sourceDocs entityDocs, docs entityDocs) {
for k, v := range sourceDocs.Arguments { // string -> argument
arguments := sourceDocs.Arguments[k].arguments
docArguments := make(map[string]string)
for kk, vv := range arguments {
docArguments[kk] = vv
}
docs.Arguments[k] = &argumentDocs{
description: v.description,
arguments: docArguments,
}
}
}
// checkIfNewDocsExist checks if the new docs root exists
func checkIfNewDocsExist(repo string) bool {
// Check if the new docs path exists
newDocsPath := filepath.Join(repo, "docs", "resources")
_, err := os.Stat(newDocsPath)
return !os.IsNotExist(err)
}
// getDocsPath finds the correct docs path for the repo/kind
func getDocsPath(repo string, kind DocKind) string {
// Check if the new docs path exists
newDocsExist := checkIfNewDocsExist(repo)
if !newDocsExist {
// If the new path doesn't exist, use the old docs path.
kindString := string([]rune(kind)[0]) // We only want the first letter because the old path uses "r" and "d"
return filepath.Join(repo, "website", "docs", kindString)
}
// Otherwise use the new location path.
kindString := string(kind)
return filepath.Join(repo, "docs", kindString)
}
// readMarkdown searches all possible locations for the markdown content
func readMarkdown(repo string, kind DocKind, possibleLocations []string) ([]byte, string, bool) {
locationPrefix := getDocsPath(repo, kind)
for _, name := range possibleLocations {
location := filepath.Join(locationPrefix, name)
markdownBytes, err := os.ReadFile(location)
if err == nil {
return markdownBytes, name, true
}
}
return nil, "", false
}
// nolint:lll
var (
// For example:
// [1]: https://docs.aws.amazon.com/lambda/latest/dg/welcome.html
linkFooterRegexp = regexp.MustCompile(`(?m)^(\[\d+\]):\s(.*)`)
argumentBulletRegexp = regexp.MustCompile(
"^\\s*[*+-]\\s+`([a-zA-z0-9_]*)`\\s*(\\([a-zA-Z]*\\)\\s*)?[–-]?\\s+(\\([^\\)]*\\)\\s*)?(.*)")
attributeBulletRegexp = regexp.MustCompile("^\\s*[*+-]\\s+`([a-zA-z0-9_]*)`\\s+[–-]?\\s+(.*)")
attributionFormatString = "This Pulumi package is based on the [`%[1]s` Terraform Provider](https://%[3]s/%[2]s/terraform-provider-%[1]s)."
)
// groupLines take a slice of strings, lines, and returns a nested slice of strings. When groupLines encounters a line
// that in the input that starts with the supplied string sep, it will begin a new entry in the outer slice.
func groupLines(lines []string, sep string) [][]string {
var buffer []string
var sections [][]string
for _, line := range lines {
if strings.Index(line, sep) == 0 {
sections = append(sections, buffer)
buffer = []string{}
}
buffer = append(buffer, line)
}
if len(buffer) > 0 {
sections = append(sections, buffer)
}
return sections
}
// splitGroupLines splits and groups a string, s, by a given separator, sep.
func splitGroupLines(s, sep string) [][]string {
return groupLines(strings.Split(s, "\n"), sep)
}
// parseTFMarkdown takes a TF website markdown doc and extracts a structured representation for use in
// generating doc comments
func parseTFMarkdown(g *Generator, info tfbridge.ResourceOrDataSourceInfo, kind DocKind,
markdown, markdownFileName, resourcePrefix, rawname string) (entityDocs, error) {
p := &tfMarkdownParser{
g: g,
info: info,
kind: kind,
markdown: markdown,
markdownFileName: markdownFileName,
resourcePrefix: resourcePrefix,
rawname: rawname,
}
return p.parse()
}
type tfMarkdownParser struct {
g *Generator
info tfbridge.ResourceOrDataSourceInfo
kind DocKind
markdown string
markdownFileName string
resourcePrefix string
rawname string
ret entityDocs
}
const (
sectionOther = 0
sectionExampleUsage = 1
sectionArgsReference = 2
sectionAttributesReference = 3
sectionFrontMatter = 4
sectionImports = 5
)
func (p *tfMarkdownParser) parseSupplementaryExamples() (string, error) {
examplesFileName := fmt.Sprintf("docs/%s/%s.examples.md", p.kind, p.rawname)
absPath, err := filepath.Abs(examplesFileName)
if err != nil {
return "", err
}
fileBytes, err := os.ReadFile(absPath)
if err != nil {
p.g.error("explicitly marked resource documention for replacement, but found no file at %q", examplesFileName)
return "", err
}
return string(fileBytes), nil
}
func (p *tfMarkdownParser) parse() (entityDocs, error) {
p.ret = entityDocs{
Arguments: make(map[string]*argumentDocs),
Attributes: make(map[string]string),
}
// Replace any Windows-style newlines.
markdown := strings.Replace(p.markdown, "\r\n", "\n", -1)
// Replace redundant comment.
markdown = strings.Replace(markdown, "<!-- schema generated by tfplugindocs -->", "", -1)
// Split the sections by H2 topics in the Markdown file.
sections := splitGroupLines(markdown, "## ")
// we are explicitly overwriting the Terraform examples here
if p.info != nil && p.info.GetDocs() != nil && p.info.ReplaceExamplesSection() {
for i, section := range sections {
// Let's remove any existing examples usage we have in our parsed documentation
if len(section) > 0 && strings.Contains(section[0], "Example Usage") {
sections = append(sections[:i], sections[i+1:]...)
break
}
}
// now we are going to inject the new source of examples
newExamples, err := p.parseSupplementaryExamples()
if err != nil {
return entityDocs{}, err
}
newSection := strings.Split(newExamples, "\n")
sections = append(sections, newSection)
} else {
// Reparent examples that are peers of the "Example Usage" section (if any) and fixup some example titles.
sections = reformatExamples(sections)
}
for _, section := range sections {
if err := p.parseSection(section); err != nil {
return entityDocs{}, err
}
}
// Get links.
footerLinks := getFooterLinks(markdown)
doc, _ := cleanupDoc(p.rawname, p.g, p.ret, footerLinks)
return doc, nil
}
// fixExampleTitles transforms H4 sections that contain code snippets into H3 sections.
func fixExampleTitles(lines []string) {
inSection, sectionIndex := false, 0
for i, line := range lines {
if inSection && strings.HasPrefix(line, "```") {
lines[sectionIndex] = strings.Replace(lines[sectionIndex], "#### ", "### ", 1)
inSection = false
} else if strings.HasPrefix(line, "#### ") {
inSection, sectionIndex = true, i
}
}
}
var exampleHeaderRegexp = regexp.MustCompile(`(?i)^(## Example Usage\s*)(?:(?:(?:for|of|[\pP]+)\s*)?(.*?)\s*)?$`)
// reformatExamples reparents examples that are peers of the "Example Usage" section (if any) and fixup some example
// titles.
func reformatExamples(sections [][]string) [][]string {
canonicalExampleUsageSectionIndex := -1
var exampleUsageSection []string
var exampleSectionIndices []int
for i, s := range sections {
matches := exampleHeaderRegexp.FindStringSubmatch(s[0])
if len(matches) == 0 {
continue
}
if len(matches[1]) == len(s[0]) {
// This is the canonical example usage section. Prepend its contents to any other content we've collected.
// If there are multiple canonical example usage sections, treat the first such section as the canonical
// example usage section and append other sections under an H3.
if canonicalExampleUsageSectionIndex == -1 {
canonicalExampleUsageSectionIndex = i
// Copy the section over. Note that we intentionally avoid copying the first line and any whitespace
// that follows it, as we will overwrite that content with the canonical header later.
for s = s[1:]; len(s) > 0 && isBlank(s[0]); s = s[1:] {
}
sectionCopy := make([]string, len(s)+2)
copy(sectionCopy[2:], s)
if len(exampleUsageSection) != 0 {
exampleUsageSection = append(sectionCopy, exampleUsageSection...)
} else {
exampleUsageSection = sectionCopy
}
} else {
exampleUsageSection = append(exampleUsageSection, "", "### Additional Examples")
exampleUsageSection = append(exampleUsageSection, s[1:]...)
}
} else if strings.Contains(s[0], "## Example Usage -") {
// this is a specific usecase where all of the examples are being requalified as top level examples with a
// title. We should process these as children of the top level examples
exampleUsageSection = append(exampleUsageSection, "### "+cases.Title(language.Und, cases.NoLower).String(matches[2]))
exampleUsageSection = append(exampleUsageSection, s[1:]...)
} else {
// This is a qualified example usage section. Retitle it using an H3 and its qualifier, and append it to
// the output.
exampleUsageSection = append(exampleUsageSection, "", "### "+
cases.Title(language.Und, cases.NoLower).String(matches[2]))
exampleUsageSection = append(exampleUsageSection, s[1:]...)
}
exampleSectionIndices = append(exampleSectionIndices, i)
}
if len(exampleSectionIndices) == 0 {
return sections
}
// If we did not find a canonical example usage section, prepend a blank line to the output. This line will be
// replaced by the canonical example usage H2.
if canonicalExampleUsageSectionIndex == -1 {
canonicalExampleUsageSectionIndex = exampleSectionIndices[0]
exampleUsageSection = append([]string{""}, exampleUsageSection...)
}
// Ensure that the output begins with the canonical example usage header.
exampleUsageSection[0] = "## Example Usage"
// Fixup example titles and replace the contents of the canonical example usage section with the output.
fixExampleTitles(exampleUsageSection)
sections[canonicalExampleUsageSectionIndex] = exampleUsageSection
// If there is only one example section, we're done. Otherwise, we need to remove all non-canonical example usage
// sections.
if len(exampleSectionIndices) == 1 {
return sections
}
result := sections[:0]
for i, s := range sections {
if len(exampleSectionIndices) > 0 && i == exampleSectionIndices[0] {
exampleSectionIndices = exampleSectionIndices[1:]
if i != canonicalExampleUsageSectionIndex {
continue
}
}
result = append(result, s)
}
return result
}
func (p *tfMarkdownParser) parseSection(h2Section []string) error {
// Extract the header name, since this will drive how we process the content.
if len(h2Section) == 0 {
p.g.warn("Unparseable H2 doc section for %v; consider overriding doc source location", p.rawname)
return nil
}
// Skip certain headers that we don't support.
header := h2Section[0]
if strings.Index(header, "## ") == 0 {
header = header[3:]
}
sectionKind := sectionOther
switch header {
case "Timeout", "Timeouts", "User Project Override", "User Project Overrides":
p.g.debug("Ignoring doc section [%v] for [%v]", header, p.rawname)
ignoredDocHeaders[header]++
return nil
case "Example Usage":
sectionKind = sectionExampleUsage
case "Arguments Reference", "Argument Reference", "Argument reference", "Nested Blocks", "Nested blocks":
sectionKind = sectionArgsReference
case "Attributes Reference", "Attribute Reference", "Attribute reference":
sectionKind = sectionAttributesReference
case "Import", "Imports":
sectionKind = sectionImports
case "---":
sectionKind = sectionFrontMatter
case "Schema":
p.parseSchemaWithNestedSections(h2Section)
return nil
}
// Now split the sections by H3 topics. This is done because we'll ignore sub-sections with code
// snippets that are unparseable (we don't want to ignore entire H2 sections).
var wroteHeader bool
for _, h3Section := range groupLines(h2Section[1:], "### ") {
if len(h3Section) == 0 {
// An unparseable H3 appears (as observed by building a few tier 1 providers) to typically be due to an
// empty section resulting from how we parse sections earlier in the docs generation process. Therefore, we
// log it as debug output:
p.g.debug("empty or unparseable H3 doc section for %v; consider overriding doc source location", p.rawname, p.kind)
continue
}
// Remove the "Open in Cloud Shell" button if any and check for the presence of code snippets.
reformattedH3Section, hasExamples, isEmpty := p.reformatSubsection(h3Section)
if isEmpty {
// Skip empty subsections (they just add unnecessary padding and headers).
continue
}
if hasExamples && sectionKind != sectionExampleUsage && sectionKind != sectionImports &&
!p.info.ReplaceExamplesSection() {
p.g.warn("Unexpected code snippets in section '%v' for %v '%v'. The HCL code will be converted if possible, "+
"but may not display correctly in the generated docs.", header, p.kind, p.rawname)
unexpectedSnippets++
}
// Now process the content based on the H2 topic. These are mostly standard across TF's docs.
switch sectionKind {
case sectionArgsReference:
p.parseArgReferenceSection(reformattedH3Section)
case sectionAttributesReference:
p.parseAttributesReferenceSection(reformattedH3Section)
case sectionFrontMatter:
p.parseFrontMatter(reformattedH3Section)
case sectionImports:
p.parseImports(reformattedH3Section)
default:
// Determine if this is a nested argument section.
_, isArgument := p.ret.Arguments[header]
if isArgument || strings.HasSuffix(header, "Configuration Block") {
p.parseArgReferenceSection(reformattedH3Section)
continue
}
// For all other sections, append them to the description section.
if !wroteHeader {
p.ret.Description += fmt.Sprintf("## %s\n", header)
wroteHeader = true
if !isBlank(reformattedH3Section[0]) {
p.ret.Description += "\n"
}
}
p.ret.Description += strings.Join(reformattedH3Section, "\n") + "\n"
}
}
return nil
}
func getFooterLinks(markdown string) map[string]string {
links := make(map[string]string)
lines := strings.Split(markdown, "\n")
for _, line := range lines {
matches := linkFooterRegexp.FindStringSubmatch(line)
if len(matches) == 3 {
links[matches[1]] = matches[2]
}
}
return links
}
func (p *tfMarkdownParser) parseSchemaWithNestedSections(subsection []string) {
node := parseNode(strings.Join(subsection, "\n"))
topLevelSchema, err := parseTopLevelSchema(node, nil)
if err != nil {
p.g.warn(fmt.Sprintf("error: Failure in parsing resource name: %s, subsection: %s", p.rawname, subsection[0]))
return
}
if topLevelSchema == nil {
p.g.warn("Failed to parse top-level Schema section")
return
}
parseTopLevelSchemaIntoDocs(&p.ret, topLevelSchema, p.g.warn)
}
// parseArgFromMarkdownLine takes a line of Markdown and attempts to parse it for a Terraform argument and its
// description
func parseArgFromMarkdownLine(line string) (string, string, bool) {
argumentBulletRegexp = regexp.MustCompile(
"^\\s*[*+-]\\s+`([a-zA-z0-9_]*)`\\s*(\\([a-zA-Z]*\\)\\s*)?[–-]?\\s+(\\([^\\)]*\\)\\s*)?(.*)")
matches := argumentBulletRegexp.FindStringSubmatch(line)
if len(matches) > 4 {
return matches[1], matches[4], true
}
return "", "", false
}
// getNestedBlockName take a line of a Terraform docs Markdown page and returns the name of the nested block it
// describes. If the line does not describe a nested block, an empty string is returned.
//
// Examples of nested blocks include (but are not limited to):
//
// - "The `private_cluster_config` block supports:" -> "private_cluster_config"
// - "The optional settings.backup_configuration subblock supports:" -> "settings.backup_configuration"
func getNestedBlockName(line string) string {
nested := ""
nestedObjectRegexps := []*regexp.Regexp{
// For example:
// s3_bucket.html.markdown: "The `website` object supports the following:"
// ami.html.markdown: "When `virtualization_type` is "hvm" the following additional arguments apply:"
regexp.MustCompile("`([a-z_]+)`.*following"),
// For example:
// athena_workgroup.html.markdown: "#### result_configuration Argument Reference"
regexp.MustCompile("(?i)## ([a-z_]+).* argument reference"),
}
for _, match := range nestedObjectRegexps {
matches := match.FindStringSubmatch(line)
if len(matches) >= 2 {
nested = strings.ToLower(matches[1])
break
}
}
return nested
}
func (p *tfMarkdownParser) parseArgReferenceSection(subsection []string) {
var lastMatch, nested string
for _, line := range subsection {
name, desc, matchFound := parseArgFromMarkdownLine(line)
if matchFound {
// found a property bullet, extract the name and description
if nested != "" {
// We found this line within a nested field. We should record it as such.
if p.ret.Arguments[nested] == nil {
p.ret.Arguments[nested] = &argumentDocs{
arguments: make(map[string]string),
}
totalArgumentsFromDocs++
} else if p.ret.Arguments[nested].arguments == nil {
p.ret.Arguments[nested].arguments = make(map[string]string)
}
p.ret.Arguments[nested].arguments[name] = desc
// Also record this as a top-level argument just in case, since sometimes the recorded nested
// argument doesn't match the resource's argument.
// For example, see `cors_rule` in s3_bucket.html.markdown.
if p.ret.Arguments[name] == nil {
p.ret.Arguments[name] = &argumentDocs{
description: desc,
isNested: true, // Mark that this argument comes from a nested field.
}
}
} else {
if !strings.HasSuffix(line, "supports the following:") {
p.ret.Arguments[name] = &argumentDocs{description: desc}
totalArgumentsFromDocs++
}
}
lastMatch = name
} else if !isBlank(line) && lastMatch != "" {
// this is a continuation of the previous bullet
if nested != "" {
p.ret.Arguments[nested].arguments[lastMatch] += "\n" + strings.TrimSpace(line)
// Also update the top-level argument if we took it from a nested field.
if p.ret.Arguments[lastMatch].isNested {
p.ret.Arguments[lastMatch].description += "\n" + strings.TrimSpace(line)
}
} else {
p.ret.Arguments[lastMatch].description += "\n" + strings.TrimSpace(line)
}
} else {
// This line might declare the beginning of a nested object.
// If we do not find a "nested", then this is an empty line or there were no bullets yet.
nestedBlockCurrentLine := getNestedBlockName(line)
if nestedBlockCurrentLine != "" {
nested = nestedBlockCurrentLine
}
// Clear the lastMatch.
lastMatch = ""
}
}
}
func (p *tfMarkdownParser) parseAttributesReferenceSection(subsection []string) {
var lastMatch string
for _, line := range subsection {
matches := attributeBulletRegexp.FindStringSubmatch(line)
if len(matches) >= 2 {
// found a property bullet, extract the name and description
p.ret.Attributes[matches[1]] = matches[2]
lastMatch = matches[1]
} else if !isBlank(line) && lastMatch != "" {
// this is a continuation of the previous bullet
p.ret.Attributes[lastMatch] += "\n" + strings.TrimSpace(line)
} else {
// This is an empty line or there were no bullets yet - clear the lastMatch
lastMatch = ""
}
}
}
func (p *tfMarkdownParser) parseImports(subsection []string) {
// check for import overwrites
info := p.info
if info != nil {
docInfo := info.GetDocs()
if docInfo != nil {
importDetails := docInfo.ImportDetails
if importDetails != "" {
p.ret.Import = fmt.Sprintf("## Import\n\n%s", importDetails)
return
}
}
}
var importDocString []string
for _, section := range subsection {
if strings.Contains(section, "**NOTE:") || strings.Contains(section, "**Please Note:") ||
strings.Contains(section, "**Note:**") {
// This is a Terraform import specific comment that we don't need to parse or include in our docs
continue
}
// Skip another redundant comment
if strings.Contains(section, "Import is supported using the following syntax") {
continue
}
// Remove the shell comment characters to avoid writing this line as a Markdown H1:
section = strings.TrimPrefix(section, "# ")
// There are multiple variations of codeblocks for import syntax
section = strings.Replace(section, "```shell", "", -1)
section = strings.Replace(section, "```sh", "", -1)
section = strings.Replace(section, "```", "", -1)
if strings.Contains(section, "terraform import") {
// First, remove the `$`
section := strings.Replace(section, "$ ", "", -1)
// Next, remove `terraform import` from the codeblock
section = strings.Replace(section, "terraform import ", "", -1)
importString := ""
parts := strings.Split(section, " ")
for i, p := range parts {
switch i {
case 0:
if !isBlank(p) {
// split the string on . and take the last item
// this gets the identifier broken from the tf resource
ids := strings.Split(p, ".")
name := ids[len(ids)-1]
importString = fmt.Sprintf("%s %s", importString, name)
}
default:
if !isBlank(p) {
importString = fmt.Sprintf("%s %s", importString, p)
}
}
}
var tok string
if p.info != nil && p.info.GetTok() != "" {
tok = p.info.GetTok().String()
} else {
tok = "MISSING_TOK"
}
// We are going to use a placeholder here for the linebreak so that when we get into converting examples
// we can format our Import section outside of the examples section
importCommand := fmt.Sprintf("$ pulumi import %s%s", tok, importString)
importDetails := []string{"<break><break>```sh<break>", importCommand, "<break>```<break><break>"}
importDocString = append(importDocString, importDetails...)
} else {
if !isBlank(section) {
importDocString = append(importDocString, section)
}
}
}
if len(importDocString) > 0 {
p.ret.Import = fmt.Sprintf("## Import\n\n%s", strings.Join(importDocString, " "))
}
}
func (p *tfMarkdownParser) parseFrontMatter(subsection []string) {
// The header of the MarkDown will have two "---"s paired up to delineate the header. Skip this.
var foundEndHeader bool
for len(subsection) > 0 {
curr := subsection[0]
subsection = subsection[1:]
if curr == "---" {
foundEndHeader = true
break
}
}
if !foundEndHeader {
p.g.warn("", "Expected to pair --- begin/end for resource %v's Markdown header", p.rawname)
}
// Now extract the description section. We assume here that the first H1 (line starting with #) is the name
// of the resource, because we aren't detecting code fencing. Comments in HCL are prefixed with # (the
// same as H1 in Markdown, so we treat further H1's in this section as part of the description. If there
// are no matching H1s, we emit a warning for the resource as it is likely a problem with the documentation.
lastBlank := true
var foundH1Resource bool
for _, line := range subsection {
if strings.Index(line, "# ") == 0 {
foundH1Resource = true
lastBlank = true
} else if !isBlank(line) || !lastBlank {
p.ret.Description += line + "\n"
lastBlank = false
} else if isBlank(line) {
lastBlank = true
}
}
if !foundH1Resource {
p.g.warn("Expected an H1 in markdown for resource %v", p.rawname)
}
}
// isBlank returns true if the line is all whitespace.
func isBlank(line string) bool {
return strings.TrimSpace(line) == ""
}
// reformatSubsection strips any "Open in Cloud Shell" buttons from the subsection and detects the presence of example
// code snippets.