Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

imp: operation 'snake-free' in progress #1231

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion mgc/spec_manipulator/build.sh
Original file line number Diff line number Diff line change
@@ -1 +1 @@
go build -o specs
go build -o mgca
30 changes: 0 additions & 30 deletions mgc/spec_manipulator/cmd/download.go

This file was deleted.

162 changes: 162 additions & 0 deletions mgc/spec_manipulator/cmd/pipeline/gen_expected_cli_doc_output.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
package pipeline

import (
"encoding/json"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"strings"

"github.com/spf13/cobra"
)

type TreeNode struct {
Name string `json:"name"`
Children []TreeNode `json:"children,omitempty"`
}

func loadJSON(filename string) ([]TreeNode, error) {
data, err := os.ReadFile(filename)
if err != nil {
return nil, err
}

var tree []TreeNode
err = json.Unmarshal(data, &tree)
return tree, err
}

func iterTree(children []TreeNode, parentPath []string) [][]string {
var result [][]string
for _, child := range children {
path := append(parentPath, child.Name)
result = append(result, path)

if len(child.Children) > 0 {
result = append(result, iterTree(child.Children, path)...)
}
}
return result
}

func genCliPaths(cli string, tree []TreeNode) [][]string {
result := [][]string{{cli}}
result = append(result, iterTree(tree, []string{cli})...)
return result
}

func genOutput(cmd []string) (string, error) {
cmd = append(cmd, "--raw")
output, err := exec.Command(cmd[0], cmd[1:]...).Output()
return string(output), err
}

func genHelpOutput(path []string) (string, error) {
cmd := append([]string{path[0], "help"}, path[1:]...)
return genOutput(cmd)
}

// func genOutputHFlag(path []string) (string, error) {
// cmd := append(path, "-h")
// return genOutput(cmd)
// }

func convertToMarkdown(inputText string) string {
sections := strings.Split(inputText, "\n\n")
var markdown strings.Builder

// Header section
markdown.WriteString(fmt.Sprintf("# %s\n\n", strings.TrimSpace(sections[0])))

// Usage section
markdown.WriteString("## Usage:\n```bash\n")
markdown.WriteString(strings.TrimSpace(sections[1]))
markdown.WriteString("\n```\n\n")

// Product catalog section
markdown.WriteString("## Product catalog:\n")
for _, item := range strings.Split(strings.TrimSpace(sections[2]), "\n") {
markdown.WriteString(fmt.Sprintf("- %s\n", strings.TrimSpace(item)))
}
markdown.WriteString("\n")

// Other commands section
markdown.WriteString("## Other commands:\n")
for _, item := range strings.Split(strings.TrimSpace(sections[3]), "\n") {
markdown.WriteString(fmt.Sprintf("- %s\n", strings.TrimSpace(item)))
}
markdown.WriteString("\n")

// Flags section
markdown.WriteString("## Flags:\n```bash\n")
markdown.WriteString(strings.TrimSpace(sections[4]))
markdown.WriteString("\n```\n\n")

return markdown.String()
}

type CliDocParams struct {
cli string
dumpCliJson string
outputDir string
verbose int
}

func runDocParams(params CliDocParams) {

log.SetFlags(0)
log.SetPrefix("INF ")

if params.verbose > 0 {
log.SetPrefix("DBG ")
}

tree, err := loadJSON(params.dumpCliJson)
if err != nil {
log.Fatalf("Failed to load JSON: %v", err)
}

rootDir, _ := filepath.Abs(params.outputDir)
log.Printf("removing output-dir: %s", rootDir)
os.RemoveAll(rootDir)

for _, path := range genCliPaths(params.cli, tree) {
log.Printf("processing: %s", strings.Join(path, " "))
helpOutput, err := genHelpOutput(path)
if err != nil {
log.Printf("Error generating help output: %v", err)
continue
}
markdownOutput := convertToMarkdown(helpOutput)

outDir := filepath.Join(rootDir, filepath.Join(path[1:]...))
_ = os.MkdirAll(outDir, os.ModePerm)
filePath := filepath.Join(outDir, "help.md")
err = os.WriteFile(filePath, []byte(markdownOutput), 0644)
if err != nil {
log.Printf("Error writing file: %v", err)
} else {
log.Printf("wrote %s", filePath)
}
}
}
func CliDocOutputCmd() *cobra.Command {
options := &CliDocParams{}

cmd := &cobra.Command{
Use: "cligendoc",
Short: "run gen doc cli",
Run: func(cmd *cobra.Command, args []string) {
runDocParams(*options)
},
}

cmd.Flags().StringVarP(&options.cli, "cli", "c", "", "Local ou comando da CLI")
cmd.Flags().StringVarP(&options.outputDir, "outputdir", "o", "", "Local de saida do dump file")
cmd.Flags().StringVarP(&options.dumpCliJson, "dump", "d", "", "CLI Dump file json")
cmd.Flags().IntVarP(&options.verbose, "verbose", "v", 0, "Verbose")

return cmd
}
89 changes: 89 additions & 0 deletions mgc/spec_manipulator/cmd/pipeline/gen_expected_cli_dump_tree.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package pipeline

import (
"encoding/json"
"flag"
"fmt"
"os"
"os/exec"

"github.com/spf13/cobra"
)

func genCliDumpTree(cli string) ([]interface{}, error) {
args := []string{"dump-tree", "-o", "json", "--raw"}
cmd := exec.Command(cli, args...)

output, err := cmd.Output()
if err != nil {
return nil, fmt.Errorf("error executing command: %w", err)
}

var tree []interface{}
err = json.Unmarshal(output, &tree)
if err != nil {
return nil, fmt.Errorf("error unmarshaling JSON: %w", err)
}

return tree, nil
}

type DumpeMenu struct {
cli string
output string
}

func dumpTree(options DumpeMenu) {

if options.cli == "" {
fmt.Println("Error: cli argument is required")
flag.Usage()
os.Exit(1)
}

tree, err := genCliDumpTree(options.cli)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}

var out *os.File
if options.output == "" {
out = os.Stdout
} else {
var err error
out, err = os.Create(options.output)
if err != nil {
fmt.Fprintf(os.Stderr, "Error creating output file: %v\n", err)
os.Exit(1)
}
defer out.Close()
}

encoder := json.NewEncoder(out)
encoder.SetIndent("", " ")
encoder.SetEscapeHTML(false)
err = encoder.Encode(tree)
if err != nil {
fmt.Fprintf(os.Stderr, "Error encoding JSON: %v\n", err)
os.Exit(1)
}

}

func CliDumpTreeCmd() *cobra.Command {
options := &DumpeMenu{}

cmd := &cobra.Command{
Use: "dumptree",
Short: "run dump tree",
Run: func(cmd *cobra.Command, args []string) {
dumpTree(*options)
},
}

cmd.Flags().StringVarP(&options.cli, "cli", "c", "", "Local ou comando da CLI")
cmd.Flags().StringVarP(&options.output, "output", "o", "", "Local de saida do dump file")

return cmd
}
17 changes: 17 additions & 0 deletions mgc/spec_manipulator/cmd/pipeline/root_pipeline.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package pipeline

import (
"github.com/spf13/cobra"
)

func PipelineCmd() *cobra.Command {
pipeMenu := &cobra.Command{
Use: "pipeline",
Short: "Menu com opções uteis ao pipeline e ao pre-commit",
}

pipeMenu.AddCommand(CliDumpTreeCmd()) // download all
pipeMenu.AddCommand(CliDocOutputCmd())

return pipeMenu
}
27 changes: 7 additions & 20 deletions mgc/spec_manipulator/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,18 @@ package cmd
import (
"fmt"
"os"
"path"
"path/filepath"

"github.com/spf13/cobra"
"github.com/spf13/viper"
"magalu.cloud/mgca/cmd/pipeline"
"magalu.cloud/mgca/cmd/spec"
)

var (
rootCmd = &cobra.Command{
CompletionOptions: cobra.CompletionOptions{DisableDefaultCmd: true},
Use: "specs",
Use: "mgca",
Short: "Utilitário para auxiliar na atualização de specs",
Long: `Uma, ou mais uma CLI para ajudar no processo de atualização das specs.`,
}
Expand All @@ -24,31 +25,17 @@ const (
SPEC_DIR = "cli_specs"
)

var currentDir = func() string {
ex, err := os.Executable()
if err != nil {
panic(err)
}
exPath := filepath.Dir(ex)

return path.Join(exPath, SPEC_DIR)
}

// Execute executes the root command.
func Execute() error {
rootCmd.AddCommand(spec.SpecCmd())
rootCmd.AddCommand(pipeline.PipelineCmd())
rootCmd.AddCommand(versionCmd) // version

return rootCmd.Execute()
}

func init() {
cobra.OnInitialize(initConfig)
rootCmd.AddCommand(versionCmd) // version
rootCmd.AddCommand(downloadSpecsCmd) // download all
rootCmd.AddCommand(addSpecsCmd) // add spec
rootCmd.AddCommand(deleteSpecsCmd) // delete spec
rootCmd.AddCommand(listSpecsCmd) // list specs
rootCmd.AddCommand(prepareToGoCmd) // convert spec to golang
rootCmd.AddCommand(downgradeSpecCmd) // downgrade spec

}

func initConfig() {
Expand Down
Loading
Loading