utils

package
v2.11.26 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 3, 2024 License: Apache-2.0 Imports: 26 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// WarningColor is the color to use for warnings.
	WarningColor = color.New(color.FgHiYellow, color.Bold)
	// Warnf behaves like Sprintf for a warning color.
	Warnf = WarningColor.Sprintf
	// Heading is the color for headings.
	Heading = color.New(color.FgWhite, color.Bold)
	// Muted is the color for headings you want muted.
	Muted = color.New(color.FgBlue)
	// TipColor is the color to show for tips.
	TipColor = color.New(color.FgGreen, color.Bold)
)

Functions

func AssertJSONMap

func AssertJSONMap(jsonString []byte) (json.RawMessage, error)

AssertJSONMap asserts that the string is a JSON map.

func ConfigError

func ConfigError(err error) bool

ConfigError returns true if the error is due to user error.

func CreateProxy

func CreateProxy(w io.Writer, host, gateway string, overrideHeader http.Header) *httputil.ReverseProxy

CreateProxy creates a proxy to the specified gateway with the specified host in the request header.

func CreateProxyDirector

func CreateProxyDirector(host, gateway string, overrideHeader http.Header) func(*http.Request)

CreateProxyDirector creates a function that modifies requests being sent to a http.RoundTripper so the request is redirected to an IP other than what the domain specifies.

Example
director := CreateProxyDirector("my-app.example.com", "kf.proxy.gateway", http.Header{
	resources.KfAppMatchHeader: []string{"my-app"},
})

req, err := http.NewRequest(http.MethodGet, "http://my-app.example.com/foo", nil)
if err != nil {
	panic(err)
}

director(req)

fmt.Println("URL:", req.URL.String())
fmt.Println("Host:", req.Host)
fmt.Println("Header:", req.Header)
Output:

URL: http://kf.proxy.gateway/foo
Host: my-app.example.com
Header: map[X-Kf-App:[my-app]]

func ExperimentalCommandGroup

func ExperimentalCommandGroup(name string, cmds ...*cobra.Command) group.CommandGroup

ExperimentalCommandGroup returns a CommandGroup that has a [EXPERIMENTAL] prefix. It will alter each command to have a PersistentPreRunE that notes that it is an experiment.

func JoinHeredoc

func JoinHeredoc(docstrings ...string) string

JoinHeredoc joins documentation that was defined in-line by removing leading whitespace and joining blocks of text with two newlines.

Example
fmt.Println(JoinHeredoc(`List:

		* a
		* b
		* c
		`, // normal documentation with indentation.
	"NOTE: single line of text.",
	`



		`, // blank lines get ignored
))
Output:

List:

* a
* b
* c

NOTE: single line of text.

func NewPrefixFilter

func NewPrefixFilter(prefixes map[string]io.Writer, defaultWriter io.Writer) io.Writer

func ParseJSONOrFile

func ParseJSONOrFile(jsonOrFile string) (json.RawMessage, error)

ParseJSONOrFile parses the value as JSON if it's valid or else it tries to read the value as a file on the filesystem.

func PreviewCommandGroup

func PreviewCommandGroup(name string, cmds ...*cobra.Command) group.CommandGroup

PreviewCommandGroup returns a CommandGroup that has a [PREVIEW] prefix. It will alter each command to have a PersistentPreRunE that notes that it is in preview.

func PrintCurlExamples

func PrintCurlExamples(ctx context.Context, listener net.Listener, host, gateway string)

PrintCurlExamples lists example HTTP requests the user can send.

func PrintCurlExamplesNoListener

func PrintCurlExamplesNoListener(ctx context.Context, host, gateway string)

PrintCurlExamplesNoListener prints CURL examples against the real gateway.

func PrintNextActions

func PrintNextActions(w io.Writer)

PrintNextActions prints all the available next actions and clears their values.

func SplitTags

func SplitTags(tagsStr string) []string

SplitTags parses a string of tags into a list by splitting the string by whitespace and commas.

func StatusUpdateConditionReporter added in v2.11.16

func StatusUpdateConditionReporter(w io.Writer) func(message string)

StatusUpdateConditionReporter creates a function that prints deltas between two status updates.

Example
reporter := StatusUpdateConditionReporter(os.Stdout)

reporter("Foo")
reporter("Bar")
reporter("Bar")

// Expected: [status update] Foo
// [status update] Bar
Output:

func SuggestNextAction

func SuggestNextAction(t NextAction)

SuggestNextAction adds a next action to take to the global list of next actions.

Example
SuggestNextAction(NextAction{
	Description: "View logs",
	Commands: []string{
		"kf logs my-app",
	},
})

PrintNextActions(os.Stdout)
Output:

TIP: These other commands could be useful:
View logs:  kf logs my-app
Example (Duplicate)
for i := 0; i < 10; i++ {
	SuggestNextAction(NextAction{
		Description: "View logs",
		Commands: []string{
			"kf logs my-app",
		},
	})
}

PrintNextActions(os.Stdout)
Output:

TIP: These other commands could be useful:
View logs:  kf logs my-app

Types

type AsyncFlags

type AsyncFlags struct {
	// contains filtered or unexported fields
}

AsyncFlags is a flag set for managing whether or not a command runs asynchronously.

Example
var async AsyncFlags

cmd := &cobra.Command{
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("Running async?", async.IsAsync())
	},
}
async.Add(cmd)

cmd.SetArgs([]string{})
cmd.ExecuteC()

cmd.SetArgs([]string{"--async"})
cmd.ExecuteC()
Output:

Running async? false
Running async? true

func (*AsyncFlags) Add

func (flags *AsyncFlags) Add(cmd *cobra.Command)

Add adds the async flag to the Cobra command.

func (*AsyncFlags) AwaitAndLog

func (flags *AsyncFlags) AwaitAndLog(w io.Writer, action string, callback func() error) error

AwaitAndLog waits for the action to be completed if the flag specifies the command should run synchronously. In either case, it will notify the user of the decision by logging to the writer whether it waited or not. If an error is returned by the callback the result will be an error, otherwise the error will be nil.

func (*AsyncFlags) IsAsync

func (flags *AsyncFlags) IsAsync() bool

IsAsync returns true if the user wanted the operation to run asynchronously.

func (*AsyncFlags) IsSynchronous

func (flags *AsyncFlags) IsSynchronous() bool

IsSynchronous returns true if the user wants the operation to be completed synchronously.

Example
var async AsyncFlags

cmd := &cobra.Command{
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("Running sync?", async.IsSynchronous())
	},
}
async.Add(cmd)

cmd.SetArgs([]string{})
cmd.ExecuteC()

cmd.SetArgs([]string{"--async"})
cmd.ExecuteC()
Output:

Running sync? true
Running sync? false

func (*AsyncFlags) WaitFor

func (flags *AsyncFlags) WaitFor(
	ctx context.Context,
	w io.Writer,
	action string,
	interval time.Duration,
	callback func() (bool, error),
) error

WaitFor waits for the action to be completed (signified by the callback returning true) if the flag specifies the command should be run synchronously. In either case, it will notify the user of the decision by logging to the writer whether it waited or not. If an error is returned by the callback the result will be an error, otherwise the error will be nil.

type AsyncIfStoppedFlags added in v2.11.17

type AsyncIfStoppedFlags struct {
	AsyncFlags
	// contains filtered or unexported fields
}

func (*AsyncIfStoppedFlags) Add added in v2.11.17

func (flags *AsyncIfStoppedFlags) Add(cmd *cobra.Command)

Add adds the async and async_if_stopped flags to the cobra command

func (*AsyncIfStoppedFlags) AwaitAndLog added in v2.11.17

func (flags *AsyncIfStoppedFlags) AwaitAndLog(stopped bool, w io.Writer, action string, callback func() error) error

AwaitANdLog waits for the application to be completed if the flags and the app's stopped status determine that the command should run synchronously. In either case, it will notify the user of the decision by logging to the writer whether it waited or not. If an error is returned by the callback the result will be an error, otherwise the error will be nil

func (*AsyncIfStoppedFlags) IsAsyncIfStopped added in v2.11.17

func (flags *AsyncIfStoppedFlags) IsAsyncIfStopped() bool

IsAsyncIfStopped returns true if the user wanted the operation to run asynchronously if the app is stopped.

type Config

type Config struct {
	Namespace   string
	Args        []string
	AllArgs     []string
	Flags       map[string][]string
	SourceImage string
	Stdout      io.Writer
	Stderr      io.Writer
}

func InBuildParseConfig

func InBuildParseConfig() Config

InBuildParseConfig is used by container images that parse args and flags.

type ConfigErr

type ConfigErr struct {
	// Reason holds the error message.
	Reason string
}

ConfigErr is used to indicate that the returned error is due to a user's invalid configuration.

func (ConfigErr) Error

func (e ConfigErr) Error() string

Error implements error.

type KfPrintFlags

type KfPrintFlags struct {
	*genericclioptions.PrintFlags
}

KfPrintFlags adapts changes that have to be made to Kubernetes' PrintFlags to work with Kf's documentation and style guidelines.

func NewKfPrintFlags

func NewKfPrintFlags() *KfPrintFlags

NewKfPrintFlags creates a new KfPrintFlags.

Example
cmd := &cobra.Command{}
cmd.Flags().SortFlags = true

printFlags := NewKfPrintFlags()
printFlags.AddFlags(cmd)

cmd.Flags().VisitAll(func(flag *pflag.Flag) {
	fmt.Println(flag.Name, " ", flag.Usage)
})

// XXX: Kf expects determinstic output for these flags.
Output:

allow-missing-template-keys   If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.
output   Output format. One of: go-template|go-template-file|json|jsonpath|jsonpath-as-json|jsonpath-file|name|template|templatefile|yaml.
show-managed-fields   If true, keep the managedFields when printing objects in JSON or YAML format.
template   Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is [golang templates](http://golang.org/pkg/text/template/#pkg-overview).

func (*KfPrintFlags) AddFlags

func (f *KfPrintFlags) AddFlags(cmd *cobra.Command)

AddFlags overrides genericclioptions.PrintFlags::AddFlags.

type NextAction

type NextAction struct {
	// Description holds the user-readable description of the next action.
	// This should be short and start with a capital letter.
	Description string
	// Commands are a list of commands to show the user. These commands should be
	// equivalent e.g. a URL, a kubectl and a kf command that all achieve the
	// same action could be put together.
	Commands []string
}

NextAction is a user-facing suggested next action that can be taken after running a particular command.

type ResourceFlags

type ResourceFlags struct {
	// contains filtered or unexported fields
}

ResourceFlags is a flag set for intaking container resource requests (e.g. cpu/memory/disk).

func (*ResourceFlags) Add

func (flags *ResourceFlags) Add(cmd *cobra.Command)

Add adds the resource flags to the Cobra command.

func (*ResourceFlags) CPU

func (flags *ResourceFlags) CPU() string

CPU returns the cpu flag value.

func (*ResourceFlags) Disk

func (flags *ResourceFlags) Disk() string

Disk returns the disk flag value.

func (*ResourceFlags) Memory

func (flags *ResourceFlags) Memory() string

Memory returns the memory flag value.

type RetryFlags

type RetryFlags struct {
	// contains filtered or unexported fields
}

RetryFlags is a flag set for managing how a command retries attempts.

Example
var retry RetryFlags

cmd := &cobra.Command{
	Run: func(cmd *cobra.Command, args []string) {
		times := 0
		retry.Retry(func() error {
			fmt.Println("Running:", times)
			times++
			return errors.New("trigger-retry")
		})
	},
}
retry.Add(cmd, 3, 10*time.Millisecond)

cmd.SetArgs([]string{})
cmd.ExecuteC()
Output:

Running: 0
Running: 1
Running: 2

func (*RetryFlags) Add

func (flags *RetryFlags) Add(cmd *cobra.Command, retries int, delay time.Duration)

Add adds the retry flags to the Cobra command.

func (*RetryFlags) AddRetryForK8sPropagation

func (flags *RetryFlags) AddRetryForK8sPropagation(cmd *cobra.Command)

AddRetryForK8sPropagation sets up a retrier suitable for handling K8s propagation delays. It's guaranteed to retry more than once with a delay of >= 1 second, but specific backoff algorithm, times, delays, or jitter are subject to change.

func (*RetryFlags) Retry

func (flags *RetryFlags) Retry(callback func() error) error

Retry repeats the command the specified number of times with a delay.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL