Skip to content

Commit

Permalink
cli: choose controller output + tests
Browse files Browse the repository at this point in the history
  • Loading branch information
EwenQuim committed Feb 9, 2024
1 parent a4a610b commit ae6dd58
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 12 deletions.
33 changes: 22 additions & 11 deletions cmd/fuego/commands/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,22 @@ func Controller() *cli.Command {
Name: "controller",
Usage: "creates a new controller file",
Aliases: []string{"c"},
Flags: []cli.Flag{
&cli.StringFlag{
Name: "output",
Usage: "output file",
Aliases: []string{"o"},
},
},
Action: func(cCtx *cli.Context) error {
controllerName := "newController"
if cCtx.NArg() > 0 {
controllerName = cCtx.Args().First()
} else {
controllerName := cCtx.Args().First()

if controllerName == "" {
controllerName = "newController"
fmt.Println("Note: You can add a controller name as an argument. Example: `fuego controller books`")
}

err := createController(controllerName)
_, err := createController(controllerName, cCtx.String("output"))
if err != nil {
return err
}
Expand All @@ -36,18 +43,18 @@ func Controller() *cli.Command {
}

// createController creates a new controller file
func createController(controllerName string) error {
func createController(controllerName, outputFile string) (string, error) {
controllerDir := "./controllers/"
if _, err := os.Stat(controllerDir); os.IsNotExist(err) {
err = os.Mkdir(controllerDir, 0o755)
if err != nil {
return err
return "", err
}
}

templateContent, err := templates.FS.ReadFile("controller/controller.go")
if err != nil {
return err
return "", err
}

t := language.English
Expand All @@ -56,11 +63,15 @@ func createController(controllerName string) error {
newContent := strings.ReplaceAll(string(templateContent), "newController", controllerName)
newContent = strings.ReplaceAll(newContent, "NewController", titler.String(controllerName))

controllerPath := fmt.Sprintf("%s%s.go", controllerDir, controllerName)
controllerPath := outputFile
if controllerPath == "" {
controllerPath = fmt.Sprintf("%s%s.go", outputFile, controllerName)
}

err = os.WriteFile(controllerPath, []byte(newContent), 0o644)
if err != nil {
return err
return "", err
}

return nil
return newContent, nil
}
5 changes: 4 additions & 1 deletion cmd/fuego/commands/controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import (
)

func TestCreateController(t *testing.T) {
err := createController("books")
res, err := createController("books", "/dev/null")
require.NoError(t, err)
require.Contains(t, res, "package controller")
require.Contains(t, res, `fuego.Get(booksGroup, "/{id}", rs.getBooks)`)
require.Contains(t, res, `func (rs BooksRessources) postBooks(c *fuego.ContextWithBody[BooksCreate]) (Books, error)`)
}

0 comments on commit ae6dd58

Please sign in to comment.