Skip to content

Commit

Permalink
chore: move cmd code to pkg/cmd
Browse files Browse the repository at this point in the history
  • Loading branch information
alanconway committed Jul 18, 2024
1 parent 8f7ea7b commit adeb531
Show file tree
Hide file tree
Showing 11 changed files with 173 additions and 148 deletions.
5 changes: 3 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/tmp/
/cmd/korrel8rcli/covdata/
/cmd/korrel8rcli/korrel8rcli
_covdata/
_korrel8rcli
bin
36 changes: 18 additions & 18 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,43 +1,43 @@

all: build lint test
all: lint test build

VERSION=0.0.3

KORREL8RCLI=cmd/korrel8rcli/korrel8rcli
include .bingo/Variables.mk

VERSION_TXT=pkg/build/version.txt
SWAGGER_SPEC=swagger.json
SWAGGER_CLIENT=pkg/swagger
GOCOVERDIR=cmd/korrel8rcli/covdata

include .bingo/Variables.mk

build: $(KORREL8RCLI)
KORREL8RCLI=./korrel8rcli

lint: $(SWAGGER_CLIENT) $(GOLANGCI_LINT)
go mod tidy
@if grep -q github.com/korrel8r/korrel8r go.mod; then echo "ERROR: go.mod contains 'github.com/korrel8r/korrel8r'; remove this dependency."; exit 1; fi
$(GOLANGCI_LINT) run ./...
@if grep -q github.com/korrel8r/korrel8r go.mod; then \
echo "ERROR: bad dependency: remove 'github.com/korrel8r/korrel8r' from go.mod"; \
exit 1; \
fi

build: $(KORREL8RCLI)
$(KORREL8RCLI): $(VERSION_TXT) $(SWAGGER_CLIENT)
go build -o $@ ./cmd/korrel8rcli

test: $(KORREL8RCLI) $(KORREL8R)
KORREL8R=$(KORREL8R) go test -cover -race ./...
@echo -e "\\nAccumulated coverage from main_test"
go tool covdata percent -i $(GOCOVERDIR)
test:
go test -cover -race ./...
go tool covdata percent -i pkg/cmd/_covdata

clean:
rm -rf $(GOCOVERDIR) $(KORREL8RCLI) $(SWAGGER_CLIENT) $(SWAGGER_SPEC)
rm -rfv $(SWAGGER_CLIENT) $(SWAGGER_SPEC) $(KORREL8RCLI)
git clean -dfx

ifneq ($(VERSION),$(file <$(VERSION_TXT)))
.PHONY: $(VERSION_TXT) # Force update if VERSION_TXT does not match $(VERSION)
endif

$(KORREL8RCLI): $(VERSION_TXT) $(SWAGGER_CLIENT) $(shell find -name *.go)
@mkdir -p $(dir $@)
go build -cover -o $@ ./cmd/korrel8rcli

$(VERSION_TXT): $(MAKEFILE_LIST)
echo $(VERSION) > $@

$(SWAGGER_SPEC): $(KORREL8R)
$(SWAGGER_SPEC): $(KORREL8R) ## Use bingo-installed korrel8r to generate spec.
$(KORREL8R) web --spec $@

$(SWAGGER_CLIENT): $(SWAGGER_SPEC) $(SWAGGER) ## Generate client packages.
Expand Down
114 changes: 2 additions & 112 deletions cmd/korrel8rcli/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,119 +3,9 @@
package main

import (
"fmt"
"log"
"net/url"
"os"
"path/filepath"

httptransport "github.com/go-openapi/runtime/client"
"github.com/korrel8r/client/pkg/build"
"github.com/korrel8r/client/pkg/swagger/client"
"github.com/spf13/cobra"
"sigs.k8s.io/controller-runtime/pkg/client/config"
)

const (
envURL = "KORREL8RCLI_URL"
envBearerToken = "KORREL8RCLI_BEARER_TOKEN"
"github.com/korrel8r/client/pkg/cmd"
)

var (
rootCmd = &cobra.Command{
Use: "korrel8rcli COMMAND",
Short: "REST client for a remote korrel8r server.",
Version: build.Version,
}

// Global Flags
output = EnumFlag("yaml", "json-pretty", "json")
korrel8rURL = rootCmd.PersistentFlags().StringP("url", "u", urlDefault(),
fmt.Sprintf("URL of remote korrel8r. Default from env %v", envURL))
insecure = rootCmd.PersistentFlags().BoolP("insecure", "k", false, "Insecure connection, skip TLS verification.")
// NOTE don't show the bearer token default for security reasons.
bearerTokenFlag = rootCmd.PersistentFlags().StringP("bearer-token", "t", "",
fmt.Sprintf("Authhorization token. Default from %v or kube config.", envBearerToken))
debug = rootCmd.PersistentFlags().BoolP("debug", "d", false, "Enable debug output.")
)

func urlDefault() string {
if u := os.Getenv(envURL); u != "" {
return u
}
return "http://localhost:8080"
}
func bearerToken() string {
if *bearerTokenFlag != "" { // Flag first
return *bearerTokenFlag
}
if token := os.Getenv(envBearerToken); token != "" { // Env next
return token
}
if cfg, err := config.GetConfig(); err == nil { // Kube config last
if cfg.BearerTokenFile != "" { // Try the file first
if b, err := os.ReadFile(cfg.BearerTokenFile); err == nil {
return string(b)
}
}
return cfg.BearerToken
}
return ""
}

func main() {
rootCmd.PersistentFlags().VarP(output, "output", "o", "Output format")
log.SetPrefix(filepath.Base(os.Args[0]) + ": ")
log.SetFlags(0)
check(rootCmd.Execute())
}

var versionCmd = &cobra.Command{
Use: "version",
Short: "Print version.",
Run: func(cmd *cobra.Command, args []string) { fmt.Println(rootCmd.Version) },
}

func init() {
rootCmd.AddCommand(versionCmd)
}

func newClient() *client.RESTAPI {
if *korrel8rURL == "" {
check(fmt.Errorf("Either command line flag --url or environment variable %v be set.", envURL))
}
u, err := url.Parse(*korrel8rURL)
check(err)
if u.Path == "" || u.Path == "/" {
u.Path = client.DefaultBasePath
}
var transport *httptransport.Runtime
if *insecure {
tlsClient, err := httptransport.TLSClient(httptransport.TLSClientOptions{InsecureSkipVerify: *insecure})
check(err)
transport = httptransport.NewWithClient(u.Host, u.Path, []string{u.Scheme}, tlsClient)
} else {
transport = httptransport.New(u.Host, u.Path, []string{u.Scheme})
}
if token := bearerToken(); token != "" {
transport.DefaultAuthentication = httptransport.BearerToken(token)
}
transport.Debug = *debug
return client.New(transport, nil)
}

func check(err error) {
if err == nil {
return
}
if hasPayload, ok := err.(interface{ GetPayload() any }); ok {
if m, ok := hasPayload.GetPayload().(map[string]any); ok {
if msg := m["error"]; msg != "" {
fmt.Fprintln(os.Stderr, msg)
os.Exit(1)
}
}
}
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
cmd.Main()
}
2 changes: 1 addition & 1 deletion cmd/korrel8rcli/doc.go → pkg/cmd/doc.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Copyright: This file is part of korrel8r, released under https://github.com/korrel8r/korrel8r/blob/main/LICENSE

package main
package cmd

import (
"time"
Expand Down
2 changes: 1 addition & 1 deletion cmd/korrel8rcli/enum_flag.go → pkg/cmd/enum_flag.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Copyright: This file is part of korrel8r, released under https://github.com/korrel8r/korrel8r/blob/main/LICENSE

package main
package cmd

import (
"fmt"
Expand Down
121 changes: 121 additions & 0 deletions pkg/cmd/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
// Copyright: This file is part of korrel8r, released under https://github.com/korrel8r/korrel8r/blob/main/LICENSE

package cmd

import (
"fmt"
"log"
"net/url"
"os"
"path/filepath"

httptransport "github.com/go-openapi/runtime/client"
"github.com/korrel8r/client/pkg/build"
"github.com/korrel8r/client/pkg/swagger/client"
"github.com/spf13/cobra"
"sigs.k8s.io/controller-runtime/pkg/client/config"
)

func Main() {
rootCmd.PersistentFlags().VarP(output, "output", "o", "Output format")
log.SetPrefix(filepath.Base(os.Args[0]) + ": ")
log.SetFlags(0)
check(rootCmd.Execute())
}

const (
envURL = "KORREL8RCLI_URL"
envBearerToken = "KORREL8RCLI_BEARER_TOKEN"
)

var (
rootCmd = &cobra.Command{
Use: "korrel8rcli COMMAND",
Short: "REST client for a remote korrel8r server.",
Version: build.Version,
}

// Global Flags
output = EnumFlag("yaml", "json-pretty", "json")
korrel8rURL = rootCmd.PersistentFlags().StringP("url", "u", urlDefault(),
fmt.Sprintf("URL of remote korrel8r. Default from env %v", envURL))
insecure = rootCmd.PersistentFlags().BoolP("insecure", "k", false, "Insecure connection, skip TLS verification.")
// NOTE don't show the bearer token default for security reasons.
bearerTokenFlag = rootCmd.PersistentFlags().StringP("bearer-token", "t", "",
fmt.Sprintf("Authhorization token. Default from %v or kube config.", envBearerToken))
debug = rootCmd.PersistentFlags().BoolP("debug", "d", false, "Enable debug output.")
)

func urlDefault() string {
if u := os.Getenv(envURL); u != "" {
return u
}
return "http://localhost:8080"
}
func bearerToken() string {
if *bearerTokenFlag != "" { // Flag first
return *bearerTokenFlag
}
if token := os.Getenv(envBearerToken); token != "" { // Env next
return token
}
if cfg, err := config.GetConfig(); err == nil { // Kube config last
if cfg.BearerTokenFile != "" { // Try the file first
if b, err := os.ReadFile(cfg.BearerTokenFile); err == nil {
return string(b)
}
}
return cfg.BearerToken
}
return ""
}

var versionCmd = &cobra.Command{
Use: "version",
Short: "Print version.",
Run: func(cmd *cobra.Command, args []string) { fmt.Println(rootCmd.Version) },
}

func init() {
rootCmd.AddCommand(versionCmd)
}

func newClient() *client.RESTAPI {
if *korrel8rURL == "" {
check(fmt.Errorf("Either command line flag --url or environment variable %v be set.", envURL))
}
u, err := url.Parse(*korrel8rURL)
check(err)
if u.Path == "" || u.Path == "/" {
u.Path = client.DefaultBasePath
}
var transport *httptransport.Runtime
if *insecure {
tlsClient, err := httptransport.TLSClient(httptransport.TLSClientOptions{InsecureSkipVerify: *insecure})
check(err)
transport = httptransport.NewWithClient(u.Host, u.Path, []string{u.Scheme}, tlsClient)
} else {
transport = httptransport.New(u.Host, u.Path, []string{u.Scheme})
}
if token := bearerToken(); token != "" {
transport.DefaultAuthentication = httptransport.BearerToken(token)
}
transport.Debug = *debug
return client.New(transport, nil)
}

func check(err error) {
if err == nil {
return
}
if hasPayload, ok := err.(interface{ GetPayload() any }); ok {
if m, ok := hasPayload.GetPayload().(map[string]any); ok {
if msg := m["error"]; msg != "" {
fmt.Fprintln(os.Stderr, msg)
os.Exit(1)
}
}
}
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
Loading

0 comments on commit adeb531

Please sign in to comment.