kubevela/hack/docgen/gen.go

100 lines
2.3 KiB
Go
Raw Normal View History

/*
Copyright 2021 The KubeVela 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"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"github.com/oam-dev/kubevela/references/cli"
"github.com/spf13/cobra/doc"
)
func main() {
rootPath := "../kubevela.io/docs/cli/"
if len(os.Args) > 1 {
rootPath = os.Args[1]
}
fmt.Println("scanning rootPath of CLI docs for replace: ", rootPath)
vela := cli.NewCommand()
err := doc.GenMarkdownTree(vela, rootPath)
if err != nil {
log.Fatal(err)
}
err = filepath.Walk(rootPath, func(path string, info fs.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
data, err := ioutil.ReadFile(path)
if err != nil {
return err
}
lines := strings.Split(string(data), "\n")
if len(lines) < 1 {
return nil
}
// check first line to make sure it's autogenerated docs
firstL := lines[0]
if !strings.HasPrefix(firstL, "## vela") {
return nil
}
// find the last line and add some link.
var lastIdx int
for idx := len(lines) - 1; idx >= 0; idx-- {
if strings.Contains(lines[idx], "Auto generated") {
lastIdx = idx
break
}
}
if lastIdx == 0 {
return nil
}
lastL := lines[lastIdx]
lines[lastIdx] = lastL + ", refer to [script in KubeVela](https://github.com/oam-dev/kubevela/tree/master/hack/docgen)."
// update the title format
title := strings.TrimPrefix(firstL, "## ")
lines[0] = "---"
newlines := []string{"---", "title: " + title}
for idx, line := range lines {
if strings.Contains(line, ".md") && strings.Contains(line, "](") {
lines[idx] = strings.Replace(line, ".md", "", -1)
}
}
newlines = append(newlines, lines...)
newcontent := strings.Join(newlines, "\n")
return ioutil.WriteFile(path, []byte(newcontent), info.Mode())
})
if err != nil {
log.Fatal(err)
}
}