Skip to content

Commit

Permalink
Added a general print function.
Browse files Browse the repository at this point in the history
  • Loading branch information
OliverLok committed Dec 5, 2024
1 parent 9ae5114 commit b812089
Show file tree
Hide file tree
Showing 6 changed files with 101 additions and 113 deletions.
22 changes: 0 additions & 22 deletions cmd/call-api-endpoint/expected_output_test.go

This file was deleted.

22 changes: 22 additions & 0 deletions cmd/call-endpoint/expected_output_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package main

const EXPECTED_SERVER_USER_LIST_TABLE = `email name role type courses
[email protected] course-admin user server {"course-languages":{"id":"course-languages","name":"Course Using Different Languages.","role":"admin"},"course101":{"id":"course101","name":"Course 101","role":"admin"}}
[email protected] course-grader user server {"course-languages":{"id":"course-languages","name":"Course Using Different Languages.","role":"grader"},"course101":{"id":"course101","name":"Course 101","role":"grader"}}
[email protected] course-other user server {"course-languages":{"id":"course-languages","name":"Course Using Different Languages.","role":"other"},"course101":{"id":"course101","name":"Course 101","role":"other"}}
[email protected] course-owner user server {"course-languages":{"id":"course-languages","name":"Course Using Different Languages.","role":"owner"},"course101":{"id":"course101","name":"Course 101","role":"owner"}}
[email protected] course-student user server {"course-languages":{"id":"course-languages","name":"Course Using Different Languages.","role":"student"},"course101":{"id":"course101","name":"Course 101","role":"student"}}
root root root server {}
[email protected] server-admin admin server {}
[email protected] server-creator creator server {}
[email protected] server-owner owner server {}
[email protected] server-user user server {}
`

const EXPECTED_COURSE_USER_LIST_TABLE = `email lms-id name role type
[email protected] [email protected] course-admin admin course
[email protected] [email protected] course-grader grader course
[email protected] [email protected] course-other other course
[email protected] [email protected] course-owner owner course
[email protected] [email protected] course-student student course
`
86 changes: 73 additions & 13 deletions cmd/call-api-endpoint/main.go → cmd/call-endpoint/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"fmt"
"sort"
"strings"

"github.com/alecthomas/kong"
Expand All @@ -11,6 +12,7 @@ import (
"github.com/edulinq/autograder/internal/cmd"
"github.com/edulinq/autograder/internal/config"
"github.com/edulinq/autograder/internal/log"
"github.com/edulinq/autograder/internal/util"
)

var args struct {
Expand All @@ -19,9 +21,15 @@ var args struct {

Endpoint string `help:"Endpoint of the desired API." arg:""`
Parameters []string `help:"Parameter for the endpoint in the format 'key:value', e.g., 'id:123'." arg:"" optional:""`
Table bool `help:"Output data as a TSV (only supported for specific endpoints; see help for more info)." default:"false"`
Table bool `help:"Attempt to output data as a TSV. Will default to JSON." default:"false"`
}

const (
USERS = "users"
COURSES = "courses"
TYPE = "type"
)

func main() {
kong.Parse(&args,
kong.Description(generateHelpDescription()),
Expand Down Expand Up @@ -68,13 +76,7 @@ func main() {

var printFunc cmd.CustomResponseFormatter
if args.Table {
printFunc = cmd.EndpointCustomFormatters[args.Endpoint]
if printFunc == nil {
log.Fatal("Table formatting is not supported for the specified endpoint.", log.NewAttr("endpoint", args.Endpoint))

// Return to prevent further execution after log.Fatal().
return
}
printFunc = printCMDResponseTable
}

cmd.MustHandleCMDRequestAndExitFull(args.Endpoint, request, nil, args.CommonOptions, printFunc)
Expand All @@ -91,12 +93,70 @@ func generateHelpDescription() string {
endpointList.WriteString(fmt.Sprintf(" - %s\n", endpoint))
}

var customOutputEndpointList strings.Builder
customOutputEndpointList.WriteString("Endpoints supporting TSV formatting:\n")
return baseDescription + endpointList.String()
}

func printCMDResponseTable(response core.APIResponse) string {
responseContent, ok := response.Content.(map[string]any)
if !ok {
return ""
}

users, ok := responseContent[USERS].([]any)
if !ok {
return ""
}

firstUser, ok := users[0].(map[string]any)
if !ok {
return ""
}

var headers []string
for key := range firstUser {
if key == COURSES {
continue
}
headers = append(headers, key)
}

sort.Strings(headers)

// Add courses to the end of the slice for better readability in the output.
_, exists := firstUser[COURSES]
if exists {
headers = append(headers, COURSES)
}

var usersTable strings.Builder
usersTable.WriteString(strings.Join(headers, "\t"))

lines := strings.Split(usersTable.String(), "\t")

for endpoint := range cmd.EndpointCustomFormatters {
customOutputEndpointList.WriteString(fmt.Sprintf(" - %s\n", endpoint))
usersTable.WriteString("\n")

for i, user := range users {
userMap, ok := user.(map[string]any)
if !ok {
return ""
}

var row []string
for _, key := range lines {
switch value := userMap[key].(type) {
case string:
row = append(row, value)
default:
row = append(row, util.MustToJSON(value))
}
}

usersTable.WriteString(strings.Join(row, "\t"))

if i < len(users)-1 {
usersTable.WriteString("\n")
}
}

return baseDescription + endpointList.String() + customOutputEndpointList.String()
return usersTable.String()
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,16 +39,6 @@ func TestCallApiEndpointBase(test *testing.T) {
"target-submission:1697406256",
},
},
{
CommonCMDTestCase: cmd.CommonCMDTestCase{
ExpectedStderrSubstring: `Table formatting is not supported for the specified endpoint. | {"endpoint":"courses/assignments/submissions/fetch/user/peek"}`,
ExpectedExitCode: 1,
},
endpoint: "courses/assignments/submissions/fetch/user/peek",
parameters: []string{
"--table",
},
},

// Custom Output Formatters.
{
Expand Down
67 changes: 0 additions & 67 deletions internal/cmd/custom_output.go

This file was deleted.

7 changes: 6 additions & 1 deletion internal/cmd/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,13 @@ func PrintCMDResponseFull(request any, response core.APIResponse, responseType a
fmt.Printf("\nAutograder Response:\n---\n%s\n---\n", util.MustToJSONIndent(response))
}

customOutput := ""
if customPrintFunc != nil {
fmt.Println(customPrintFunc(response))
customOutput = customPrintFunc(response)
}

if len(customOutput) > 0 {
fmt.Println(customOutput)
} else if responseType == nil {
fmt.Println(util.MustToJSONIndent(response.Content))
} else {
Expand Down

0 comments on commit b812089

Please sign in to comment.