Skip to content

Commit

Permalink
Merge pull request #4983 from gofogo/chore-4260
Browse files Browse the repository at this point in the history
chore(docs): docs/flags.md generation
  • Loading branch information
k8s-ci-robot authored Jan 3, 2025
2 parents a769df6 + 0633349 commit 909519f
Show file tree
Hide file tree
Showing 6 changed files with 394 additions and 6 deletions.
5 changes: 5 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -160,3 +160,8 @@ release.prod: test
.PHONY: ko
ko:
scripts/install-ko.sh

# generate-flags-documentation: Generate documentation (docs/flags.md)
.PHONE: generate-flags-documentation
generate-flags-documentation:
go run internal/gen/docs/flags/main.go
169 changes: 169 additions & 0 deletions docs/flags.md

Large diffs are not rendered by default.

115 changes: 115 additions & 0 deletions internal/gen/docs/flags/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/*
Copyright 2017 The Kubernetes Authors.
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 main

import (
"bytes"
"fmt"
"os"
"strings"
"text/template"

cfg "sigs.k8s.io/external-dns/pkg/apis/externaldns"
)

type Flag struct {
Name string
Description string
}
type Flags []Flag

// AddFlag adds a new flag to the Flags struct
func (f *Flags) addFlag(name, description string) {
*f = append(*f, Flag{Name: name, Description: description})
}

const markdownTemplate = `# Flags
<!-- THIS FILE MUST NOT BE EDITED BY HAND -->
<!-- ON NEW FLAG ADDED PLEASE RUN 'make generate-flags-documentation' -->
| Flag | Description |
| :------ | :----------- |
{{- range . }}
| {{ .Name }} | {{ .Description }} | {{- end -}}
`

// It generates a markdown file
// with the supported flags and writes it to the 'docs/flags.md' file.
// to re-generate `docs/flags.md` execute 'go run internal/gen/main.go'
func main() {
testPath, _ := os.Getwd()
path := fmt.Sprintf("%s/docs/flags.md", testPath)
fmt.Printf("generate file '%s' with supported flags\n", path)

flags := computeFlags()
content, err := flags.generateMarkdownTable()
if err != nil {
_ = fmt.Errorf("failed to generate markdown file '%s': %v\n", path, err.Error())
}
_ = writeToFile(path, content)
}

func computeFlags() Flags {
app := cfg.App(&cfg.Config{})
modelFlags := app.Model().Flags

flags := Flags{}

for _, flag := range modelFlags {
// do not include helpers and completion flags
if strings.Contains(flag.Name, "help") || strings.Contains(flag.Name, "completion-") {
continue
}
flagString := ""
flagName := flag.Name
if flag.IsBoolFlag() {
flagName = "[no-]" + flagName
}
flagString += fmt.Sprintf("--%s", flagName)

if !flag.IsBoolFlag() {
flagString += fmt.Sprintf("=%s", flag.FormatPlaceHolder())
}
flags.addFlag(fmt.Sprintf("`%s`", flagString), flag.HelpWithEnvar())
}
return flags
}

func (f *Flags) generateMarkdownTable() (string, error) {
tmpl := template.Must(template.New("flags.md.tpl").Parse(markdownTemplate))

var b bytes.Buffer
err := tmpl.Execute(&b, f)
if err != nil {
return "", err
}
return b.String(), nil
}

func writeToFile(filename string, content string) error {
file, fileErr := os.Create(filename)
if fileErr != nil {
_ = fmt.Errorf("failed to create file: %v", fileErr)
}
defer file.Close()
_, writeErr := file.WriteString(content)
if writeErr != nil {
_ = fmt.Errorf("failed to write to file: %s", filename)
}
return nil
}
92 changes: 92 additions & 0 deletions internal/gen/docs/flags/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/*
Copyright 2017 The Kubernetes Authors.
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 main

import (
"fmt"
"io/fs"
"os"
"strings"
"testing"

"github.com/stretchr/testify/assert"
)

const pathToDocs = "%s/../../../../docs"

func TestComputeFlags(t *testing.T) {
flags := computeFlags()

if len(flags) == 0 {
t.Errorf("Expected non-zero flags, got %d", len(flags))
}

for _, flag := range flags {
if strings.Contains(flag.Name, "help") || strings.Contains(flag.Name, "completion-") {
t.Errorf("Unexpected flag: %s", flag.Name)
}
}
}

func TestGenerateMarkdownTableRenderer(t *testing.T) {
flags := Flags{
{Name: "flag1", Description: "description1"},
}

got, err := flags.generateMarkdownTable()
assert.NoError(t, err)

assert.Contains(t, got, "<!-- THIS FILE MUST NOT BE EDITED BY HAND -->")
assert.Contains(t, got, "| flag1 | description1 |")
}

func TestFlagsMdExists(t *testing.T) {
testPath, _ := os.Getwd()
fsys := os.DirFS(fmt.Sprintf(pathToDocs, testPath))
fileName := "flags.md"
st, err := fs.Stat(fsys, fileName)
assert.NoError(t, err, "expected file %s to exist", fileName)
assert.Equal(t, fileName, st.Name())
}

func TestFlagsMdUpToDate(t *testing.T) {
testPath, _ := os.Getwd()
fsys := os.DirFS(fmt.Sprintf(pathToDocs, testPath))
fileName := "flags.md"
expected, err := fs.ReadFile(fsys, fileName)
assert.NoError(t, err, "expected file %s to exist", fileName)

flags := computeFlags()
actual, err := flags.generateMarkdownTable()
assert.NoError(t, err)
assert.True(t, len(expected) == len(actual), "expected file '%s' to be up to date. execute 'make generate-flags-documentation", fileName)
}

func TestFlagsMdExtraFlagAdded(t *testing.T) {
testPath, _ := os.Getwd()
fsys := os.DirFS(fmt.Sprintf(pathToDocs, testPath))
filePath := "flags.md"
expected, err := fs.ReadFile(fsys, filePath)
assert.NoError(t, err, "expected file %s to exist", filePath)

flags := computeFlags()
flags.addFlag("new-flag", "description2")
actual, err := flags.generateMarkdownTable()

assert.NoError(t, err)
assert.NotEqual(t, string(expected), actual)
}
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ nav:
- Changelog: charts/external-dns/CHANGELOG.md
- About:
- FAQ: docs/faq.md
- Flags: docs/flags.md
- Out of Incubator: docs/20190708-external-dns-incubator.md
- Code of Conduct: code-of-conduct.md
- License: LICENSE.md
Expand Down
18 changes: 12 additions & 6 deletions pkg/apis/externaldns/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,17 @@ func allLogLevelsAsStrings() []string {

// ParseFlags adds and parses flags from command line
func (cfg *Config) ParseFlags(args []string) error {
app := App(cfg)

_, err := app.Parse(args)
if err != nil {
return err
}

return nil
}

func App(cfg *Config) *kingpin.Application {
app := kingpin.New("external-dns", "ExternalDNS synchronizes exposed Kubernetes Services and Ingresses with DNS providers.\n\nNote that all flags may be replaced with env vars - `--flag` -> `EXTERNAL_DNS_FLAG=1` or `--flag value` -> `EXTERNAL_DNS_FLAG=value`")
app.Version(Version)
app.DefaultEnvars()
Expand Down Expand Up @@ -603,10 +614,5 @@ func (cfg *Config) ParseFlags(args []string) error {

app.Flag("webhook-server", "When enabled, runs as a webhook server instead of a controller. (default: false).").BoolVar(&cfg.WebhookServer)

_, err := app.Parse(args)
if err != nil {
return err
}

return nil
return app
}

0 comments on commit 909519f

Please sign in to comment.