File: subcommand.go

package info (click to toggle)
kubecolor 0.0.20-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 352 kB
  • sloc: makefile: 13
file content (66 lines) | stat: -rw-r--r-- 1,867 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package command

import (
	"os"

	"github.com/dty1er/kubecolor/kubectl"
	"github.com/mattn/go-isatty"
)

// mocked in unit tests
var isOutputTerminal = func() bool {
	return isatty.IsTerminal(os.Stdout.Fd()) || isatty.IsCygwinTerminal(os.Stdout.Fd())
}

func ResolveSubcommand(args []string, config *KubecolorConfig) (bool, *kubectl.SubcommandInfo) {
	// subcommandFound becomes false when subcommand is not found; e.g. "kubecolor --help"
	subcommandInfo, subcommandFound := kubectl.InspectSubcommandInfo(args)

	// if --plain found, it does not colorize
	if config.Plain {
		return false, subcommandInfo
	}

	// if subcommand is not found (e.g. kubecolor --help or just "kubecolor"),
	// it is treated as help because kubectl shows help for such input
	if !subcommandFound {
		subcommandInfo.Help = true
		return true, subcommandInfo
	}

	// when the command output is not tty, shouldColorize depends on --force-colors flag.
	// For example, if the command is run in a shellscript, it should not colorize. (e.g. in "kubectl completion bash")
	// However, if user wants colored output even if the out is not tty (e.g. kubecolor get xx | grep yy)
	// it colorizes the output based on --force-colors.
	if !isOutputTerminal() {
		return config.ForceColor, subcommandInfo
	}

	// else, when the given subcommand is supported, then we colorize it
	return subcommandFound && isColoringSupported(subcommandInfo.Subcommand), subcommandInfo
}

func isColoringSupported(sc kubectl.Subcommand) bool {
	// when you add something here, it won't be colorized
	unsupported := []kubectl.Subcommand{
		kubectl.Create,
		kubectl.Delete,
		kubectl.Edit,
		kubectl.Attach,
		kubectl.Replace,
		kubectl.Completion,
		kubectl.Exec,
		kubectl.Proxy,
		kubectl.Plugin,
		kubectl.Wait,
		kubectl.Run,
	}

	for _, u := range unsupported {
		if sc == u {
			return false
		}
	}

	return true
}