Skip to content

Commit

Permalink
feat: add pterm-ci-cmd
Browse files Browse the repository at this point in the history
  • Loading branch information
MarvinJWendt committed May 14, 2021
1 parent d3bb6c2 commit 69cabc5
Show file tree
Hide file tree
Showing 3 changed files with 166 additions and 16 deletions.
18 changes: 9 additions & 9 deletions cobra-replacements.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ import (
)

// HelpFunc is a drop in replacement for spf13/cobra `HelpFunc`
func HelpFunc(rootCmd *cobra.Command) func(*cobra.Command, []string) {
func HelpFunc() func(*cobra.Command, []string) {
return func(cmd *cobra.Command, strings []string) {
var ret string

ret += generateTitleString(rootCmd)
ret += generateUsageTemplate(cmd, rootCmd)
ret += generateUsageTemplate(cmd)
ret += generateDescriptionTemplate(cmd.Long)
ret += generateCommandsTemplate(cmd.Commands())
ret += generateFlagsTemplate(cmd.Flags())
Expand All @@ -23,12 +23,12 @@ func HelpFunc(rootCmd *cobra.Command) func(*cobra.Command, []string) {
}

// FlagErrorFunc is a drop in replacement for spf13/cobra `FlagErrorFunc`
func FlagErrorFunc(rootCmd *cobra.Command) func(*cobra.Command, error) error {
func FlagErrorFunc() func(*cobra.Command, error) error {
return func(cmd *cobra.Command, err error) error {
var ret string

ret += generateTitleString(rootCmd)
ret += generateUsageTemplate(cmd, rootCmd)
ret += generateUsageTemplate(cmd)
ret += generateDescriptionTemplate(cmd.Long)
ret += generateCommandsTemplate(cmd.Commands())
ret += generateFlagsTemplate(cmd.Flags())
Expand All @@ -41,26 +41,26 @@ func FlagErrorFunc(rootCmd *cobra.Command) func(*cobra.Command, error) error {
}

// GlobalNormalizationFunc is a drop in replacement for spf13/cobra `GlobalNormalizationFunc`
func GlobalNormalizationFunc(rootCmd *cobra.Command) func(f *pflag.FlagSet, name string) pflag.NormalizedName {
func GlobalNormalizationFunc() func(f *pflag.FlagSet, name string) pflag.NormalizedName {
return rootCmd.GlobalNormalizationFunc()
}

// HelpTemplate is a drop in replacement for spf13/cobra `HelpTemplate`
func HelpTemplate(rootCmd *cobra.Command) string {
func HelpTemplate() string {
return rootCmd.HelpTemplate()
}

// UsageFunc is a drop in replacement for spf13/cobra `UsageFunc`
func UsageFunc(rootCmd *cobra.Command) func(*cobra.Command) error {
func UsageFunc() func(*cobra.Command) error {
return rootCmd.UsageFunc()
}

// UsageTemplate is a drop in replacement for spf13/cobra `UsageTemplate`
func UsageTemplate(rootCmd *cobra.Command) string {
func UsageTemplate() string {
return rootCmd.UsageTemplate()
}

// VersionTemplate is a drop in replacement for spf13/cobra `VersionTemplate`
func VersionTemplate(rootCmd *cobra.Command) string {
func VersionTemplate() string {
return pterm.Info.Sprintfln("%s is on version: %s", rootCmd.Name(), pterm.Magenta(rootCmd.Version))
}
22 changes: 15 additions & 7 deletions pcli.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,19 @@ import (
"github.com/spf13/pflag"
)

var rootCmd *cobra.Command

// SetRootCmd sets your rootCmd.
func SetRootCmd(cmd *cobra.Command) {
rootCmd = cmd
rootCmd.AddCommand(ptermCICmd)
}

// generateMarkdown generates a help document written in markdown for a command.
func generateMarkdown(cmd, rootCmd *cobra.Command) (md string) {
func generateMarkdown(cmd *cobra.Command) (md string) {
pterm.DisableColor()
md += pterm.Sprintfln("# %s", cmd.CommandPath())
md += generateUsageTemplate(cmd, rootCmd)
md += generateUsageTemplate(cmd)
md += pterm.Sprintfln("\n## Description\n\n```\n%s\n```", cmd.Long)

if len(cmd.Commands()) > 0 {
Expand Down Expand Up @@ -57,16 +65,16 @@ func generateMarkdown(cmd, rootCmd *cobra.Command) (md string) {
}

// GenerateMarkdownDocs walks trough every subcommand of rootCmd and creates a documentation written in Markdown for it.
func GenerateMarkdownDocs(command, rootCmd *cobra.Command) (markdown []string) {
markdown = append(markdown, generateMarkdown(rootCmd, rootCmd))
func GenerateMarkdownDocs(command *cobra.Command) (markdown []string) {
markdown = append(markdown, generateMarkdown(rootCmd))
for _, cmd := range command.Commands() {
markdown = append(markdown, generateMarkdown(cmd, rootCmd))
GenerateMarkdownDocs(cmd, rootCmd)
markdown = append(markdown, generateMarkdown(cmd))
GenerateMarkdownDocs(cmd)
}
return
}

func generateUsageTemplate(cmd, rootCmd *cobra.Command) string {
func generateUsageTemplate(cmd *cobra.Command) string {
var ret string

if cmd.Short != "" {
Expand Down
142 changes: 142 additions & 0 deletions pterm-ci-cmd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
package pcli

import (
"io/fs"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
"text/template"

"github.com/pterm/pterm"
"github.com/spf13/cobra"
)

// ptermCICmd represents the ptermCi command
// ! Do not delete this file. It it used inside the CI system.
var ptermCICmd = &cobra.Command{
Use: "ptermCI",
Short: "Run internal CI-System to update documentation.",
Long: `This command is used in the CI-System to generate new documentation of the CLI tool.
It should not be used outside the development of this tool.`,
Run: func(cmd *cobra.Command, args []string) {
pterm.Info.Printfln("Running PtermCI for %s", rootCmd.Name())
markdownDocs := GenerateMarkdownDocs(rootCmd)

pterm.Fatal.PrintOnError(os.RemoveAll(getPathTo("/docs/commands")))
pterm.Fatal.PrintOnError(os.MkdirAll(getPathTo("/docs/commands"), 0600))

for _, doc := range markdownDocs {
docName := strings.ReplaceAll(strings.TrimSpace(strings.TrimLeft(strings.Split(doc, "\n")[0], "# ")), " ", "_")
pterm.Fatal.PrintOnError(ioutil.WriteFile(getPathTo(pterm.Sprintf("/docs/commands/%s.md", docName)), []byte(doc), 0600))
}

project := struct {
ProjectPath string
Name string
RepoName string
UserName string
URL string
Short string
Long string
}{}

originURL := detectOriginURL()
projectParts := strings.Split(strings.TrimPrefix(originURL, "https://github.com/"), "/")

project.UserName = projectParts[0]
project.RepoName = projectParts[1]
project.ProjectPath = pterm.Sprintf("%s/%s", project.UserName, project.RepoName)
project.Name = rootCmd.Name()
project.URL = pterm.Sprintf("https://github.com/%s", project.ProjectPath)
project.Short = rootCmd.Short
project.Long = rootCmd.Long

walkOverExt("./docs", ".template.md", func(path string) {
contentBytes, err := ioutil.ReadFile(path)
content := string(contentBytes)
tmpl, err := template.New(filepath.Base(path)).Parse(content)
pterm.Fatal.PrintOnError(err)
file, err := os.OpenFile(strings.ReplaceAll(path, ".template", ""), os.O_RDWR, 0600)
pterm.Fatal.PrintOnError(err)
pterm.Fatal.PrintOnError(tmpl.Execute(file, project))
pterm.Fatal.PrintOnError(file.Close())
pterm.Fatal.PrintOnError(ioutil.WriteFile(path, []byte(content), 0600))
})

updateSidebar(markdownDocs)
input, err := ioutil.ReadFile(getPathTo("/README.md"))
pterm.Fatal.PrintOnError(err)

err = ioutil.WriteFile(getPathTo("/docs/README.md"), input, 0600)
pterm.Fatal.PrintOnError(err)
},
Hidden: true,
}

func detectOriginURL() (url string) {
out, err := exec.Command("git", "remote", "-v").Output()
pterm.Fatal.PrintOnError(err)
pterm.Debug.Printfln("Git output:\n%s", string(out))

output := string(out)

for _, s := range strings.Split(output, "\n") {
s = strings.TrimSpace(strings.TrimLeft(s, "origin"))
if strings.HasPrefix(s, "https://github.com/") && strings.Contains(s, "push") {
pterm.Debug.Printfln("Detected GitHub Repo: %s", s)
url = strings.TrimSpace(strings.TrimRight(s, "(push)"))

return
}
}

return
}

func walkOverExt(path, exts string, f func(path string)) {
_ = filepath.Walk(getPathTo(path), func(path string, info fs.FileInfo, err error) error {

for _, ext := range strings.Split(exts, ",") {
if strings.HasSuffix(path, ext) {
f(path)
}
}
return nil
})
}

func getPathTo(file string) string {
_, scriptPath, _, _ := runtime.Caller(1)
return filepath.Join(scriptPath, "../../", file)
}

func updateSidebar(docs []string) {
sidebarPath := getPathTo("./docs/_sidebar.md")
sidebarContentByte, err := ioutil.ReadFile(sidebarPath)
pterm.Fatal.PrintOnError(err)

sidebarContent := string(sidebarContentByte)

beforeRegex := regexp.MustCompile(`(?ms).*<!-- <<<PTERM-CI-COMMANDS-START>>> -->`)
afterRegex := regexp.MustCompile(`(?ms)<!-- <<<PTERM-CI-COMMANDS-END>>> -->.*`)

before := beforeRegex.FindAllString(sidebarContent, 1)[0]
after := afterRegex.FindAllString(sidebarContent, 1)[0]

var newSidebarContent string

newSidebarContent += before + "\n"

for _, doc := range docs {
docName := strings.ReplaceAll(strings.TrimSpace(strings.TrimLeft(strings.Split(doc, "\n")[0], "# ")), " ", "_")
newSidebarContent += " - [" + docName + "](commands/" + docName + ".md)\n"
}

newSidebarContent += after

pterm.Fatal.PrintOnError(ioutil.WriteFile(sidebarPath, []byte(newSidebarContent), 0600))
}

0 comments on commit 69cabc5

Please sign in to comment.