feat: add json format output to cron:list command

This makes it easier to parse output in a machine-readable format - such as when interacting with cron tasks via jq for writing tests.
This commit is contained in:
Jose Diaz-Gonzalez
2023-07-02 04:36:08 -04:00
parent afc318526c
commit 820883e60c
6 changed files with 66 additions and 16 deletions

View File

@@ -14,12 +14,12 @@ import (
)
type TemplateCommand struct {
ID string
App string
Command string
Schedule string
AltCommand string
LogFile string
ID string `json:"id"`
App string `json:"app"`
Command string `json:"command"`
Schedule string `json:"schedule"`
AltCommand string `json:"-"`
LogFile string `json:"-"`
}
func (t TemplateCommand) CronCommand() string {

View File

@@ -18,7 +18,7 @@ Manage scheduled cron tasks
Additional commands:`
helpContent = `
cron:list <app>, List scheduled cron tasks for an app
cron:list <app> [--format json|stdout], List scheduled cron tasks for an app
cron:report [<app>] [<flag>], Display report about an app
`
)

View File

@@ -20,9 +20,10 @@ func main() {
switch subcommand {
case "list":
args := flag.NewFlagSet("cron:list", flag.ExitOnError)
format := args.String("format", "stdout", "format: [ stdout | json ]")
args.Parse(os.Args[2:])
appName := args.Arg(0)
err = cron.CommandList(appName)
err = cron.CommandList(appName, *format)
case "report":
args := flag.NewFlagSet("cron:report", flag.ExitOnError)
format := args.String("format", "stdout", "format: [ stdout | json ]")

View File

@@ -1,6 +1,7 @@
package cron
import (
"encoding/json"
"fmt"
"github.com/dokku/dokku/plugins/common"
@@ -8,22 +9,40 @@ import (
)
// CommandList lists all scheduled cron tasks for a given app
func CommandList(appName string) error {
func CommandList(appName string, format string) error {
if err := common.VerifyAppName(appName); err != nil {
return err
}
if format == "" {
format = "stdout"
}
if format != "stdout" && format != "json" {
return fmt.Errorf("Invalid format specified, supported formats: json, stdout")
}
entries, err := FetchCronEntries(appName)
if err != nil {
return err
}
output := []string{"ID | Schedule | Command"}
for _, entry := range entries {
output = append(output, fmt.Sprintf("%s | %s | %s", entry.ID, entry.Schedule, entry.Command))
if format == "stdout" {
output := []string{"ID | Schedule | Command"}
for _, entry := range entries {
output = append(output, fmt.Sprintf("%s | %s | %s", entry.ID, entry.Schedule, entry.Command))
}
result := columnize.SimpleFormat(output)
fmt.Println(result)
return nil
}
result := columnize.SimpleFormat(output)
fmt.Println(result)
out, err := json.Marshal(entries)
if err != nil {
return err
}
common.Log(string(out))
return nil
}