print cscli usage in color, fix windows terminal detection (#1801)

This commit is contained in:
mmetc 2022-10-13 12:28:24 +02:00 committed by GitHub
parent 7674f907c4
commit 4b3c9c2806
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
26 changed files with 84 additions and 71 deletions

View file

@ -10,8 +10,8 @@ import (
"strconv"
"strings"
"github.com/fatih/color"
"github.com/go-openapi/strfmt"
colorable "github.com/mattn/go-colorable"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
@ -86,7 +86,7 @@ func AlertsToTable(alerts *models.GetAlertsResponse, printMachine bool) error {
fmt.Println("No active alerts")
return nil
}
alertsTable(colorable.NewColorableStdout(), alerts, printMachine)
alertsTable(color.Output, alerts, printMachine)
}
return nil
}
@ -110,12 +110,12 @@ func DisplayOneAlert(alert *models.Alert, withDetail bool) error {
fmt.Printf(" - Begin : %s\n", *alert.StartAt)
fmt.Printf(" - End : %s\n\n", *alert.StopAt)
alertDecisionsTable(colorable.NewColorableStdout(), alert)
alertDecisionsTable(color.Output, alert)
if withDetail {
fmt.Printf("\n - Events :\n")
for _, event := range alert.Events {
alertEventTable(colorable.NewColorableStdout(), event)
alertEventTable(color.Output, event)
}
}
}

View file

@ -7,7 +7,7 @@ import (
"io"
"time"
colorable "github.com/mattn/go-colorable"
"github.com/fatih/color"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
@ -92,7 +92,7 @@ Note: This command requires database direct access, so is intended to be run on
Args: cobra.ExactArgs(0),
DisableAutoGenTag: true,
Run: func(cmd *cobra.Command, arg []string) {
err := getBouncers(colorable.NewColorableStdout(), dbClient)
err := getBouncers(color.Output, dbClient)
if err != nil {
log.Fatalf("unable to list bouncers: %s", err)
}

View file

@ -6,17 +6,17 @@ import (
"net/url"
"os"
"github.com/go-openapi/strfmt"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
"github.com/crowdsecurity/crowdsec/pkg/apiclient"
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
"github.com/crowdsecurity/crowdsec/pkg/cwversion"
"github.com/crowdsecurity/crowdsec/pkg/models"
"github.com/go-openapi/strfmt"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
)
var CAPIURLPrefix string = "v2"

View file

@ -3,7 +3,7 @@ package main
import (
"fmt"
colorable "github.com/mattn/go-colorable"
"github.com/fatih/color"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
@ -173,7 +173,7 @@ func NewCollectionsCmd() *cobra.Command {
Args: cobra.ExactArgs(0),
DisableAutoGenTag: true,
Run: func(cmd *cobra.Command, args []string) {
ListItems(colorable.NewColorableStdout(), []string{cwhub.COLLECTIONS}, args, false, true, all)
ListItems(color.Output, []string{cwhub.COLLECTIONS}, args, false, true, all)
},
}
cmdCollectionsList.PersistentFlags().BoolVarP(&all, "all", "a", false, "List disabled items as well")

View file

@ -8,15 +8,14 @@ import (
"path/filepath"
"github.com/antonmedv/expr"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
"github.com/crowdsecurity/crowdsec/pkg/types"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
)
type OldAPICfg struct {

View file

@ -10,8 +10,8 @@ import (
"net/url"
"os"
"github.com/fatih/color"
"github.com/go-openapi/strfmt"
colorable "github.com/mattn/go-colorable"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
@ -194,7 +194,7 @@ Disable given information push to the central API.`,
Run: func(cmd *cobra.Command, args []string) {
switch csConfig.Cscli.Output {
case "human":
cmdConsoleStatusTable(colorable.NewColorableStdout(), *csConfig)
cmdConsoleStatusTable(color.Output, *csConfig)
case "json":
data, err := json.MarshalIndent(csConfig.API.Server.ConsoleConfig, "", " ")
if err != nil {

View file

@ -13,11 +13,11 @@ import (
"unicode"
"github.com/AlecAivazis/survey/v2"
"github.com/crowdsecurity/crowdsec/pkg/metabase"
"github.com/pbnjay/memory"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/crowdsecurity/crowdsec/pkg/metabase"
)
var (

View file

@ -12,9 +12,9 @@ import (
"strings"
"time"
"github.com/fatih/color"
"github.com/go-openapi/strfmt"
"github.com/jszwec/csvutil"
colorable "github.com/mattn/go-colorable"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
@ -97,7 +97,7 @@ func DecisionsToTable(alerts *models.GetAlertsResponse, printMachine bool) error
fmt.Println("No active decisions")
return nil
}
decisionsTable(colorable.NewColorableStdout(), alerts, printMachine)
decisionsTable(color.Output, alerts, printMachine)
if skipped > 0 {
fmt.Printf("%d duplicated entries skipped\n", skipped)
}

View file

@ -8,10 +8,11 @@ import (
"os/exec"
"path/filepath"
"github.com/crowdsecurity/crowdsec/pkg/cstest"
"github.com/crowdsecurity/crowdsec/pkg/types"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/crowdsecurity/crowdsec/pkg/cstest"
"github.com/crowdsecurity/crowdsec/pkg/types"
)
func NewExplainCmd() *cobra.Command {

View file

@ -3,7 +3,7 @@ package main
import (
"fmt"
colorable "github.com/mattn/go-colorable"
"github.com/fatih/color"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
@ -57,7 +57,7 @@ cscli hub update # Download list of available configurations from the hub
log.Info(v)
}
cwhub.DisplaySummary()
ListItems(colorable.NewColorableStdout(), []string{
ListItems(color.Output, []string{
cwhub.COLLECTIONS, cwhub.PARSERS, cwhub.SCENARIOS, cwhub.PARSERS_OVFLW,
}, args, true, false, all)
},

View file

@ -10,7 +10,7 @@ import (
"github.com/AlecAivazis/survey/v2"
"github.com/enescakir/emoji"
colorable "github.com/mattn/go-colorable"
"github.com/fatih/color"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
@ -273,7 +273,7 @@ cscli hubtest create my-scenario-test --parsers crowdsecurity/nginx --scenarios
}
}
if csConfig.Cscli.Output == "human" {
hubTestResultTable(colorable.NewColorableStdout(), testResult)
hubTestResultTable(color.Output, testResult)
} else if csConfig.Cscli.Output == "json" {
jsonResult := make(map[string][]string, 0)
jsonResult["success"] = make([]string, 0)
@ -355,7 +355,7 @@ cscli hubtest create my-scenario-test --parsers crowdsecurity/nginx --scenarios
switch csConfig.Cscli.Output {
case "human":
hubTestListTable(colorable.NewColorableStdout(), HubTest.Tests)
hubTestListTable(color.Output, HubTest.Tests)
case "json":
j, err := json.MarshalIndent(HubTest.Tests, " ", " ")
if err != nil {
@ -430,11 +430,11 @@ cscli hubtest create my-scenario-test --parsers crowdsecurity/nginx --scenarios
if csConfig.Cscli.Output == "human" {
if showParserCov || showAll {
hubTestParserCoverageTable(colorable.NewColorableStdout(), parserCoverage)
hubTestParserCoverageTable(color.Output, parserCoverage)
}
if showScenarioCov || showAll {
hubTestScenarioCoverageTable(colorable.NewColorableStdout(), scenarioCoverage)
hubTestScenarioCoverageTable(color.Output, scenarioCoverage)
}
fmt.Println()
if showParserCov || showAll {

View file

@ -7,16 +7,17 @@ import (
"os"
"strings"
"github.com/crowdsecurity/crowdsec/pkg/apiclient"
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
"github.com/crowdsecurity/crowdsec/pkg/cwversion"
"github.com/crowdsecurity/crowdsec/pkg/models"
"github.com/go-openapi/strfmt"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
"github.com/crowdsecurity/crowdsec/pkg/apiclient"
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
"github.com/crowdsecurity/crowdsec/pkg/cwversion"
"github.com/crowdsecurity/crowdsec/pkg/models"
)
var LAPIURLPrefix string = "v1"

View file

@ -13,9 +13,9 @@ import (
"github.com/AlecAivazis/survey/v2"
"github.com/enescakir/emoji"
"github.com/fatih/color"
"github.com/go-openapi/strfmt"
"github.com/google/uuid"
colorable "github.com/mattn/go-colorable"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
@ -189,7 +189,7 @@ Note: This command requires database direct access, so is intended to be run on
}
},
Run: func(cmd *cobra.Command, args []string) {
err := getAgents(colorable.NewColorableStdout(), dbClient)
err := getAgents(color.Output, dbClient)
if err != nil {
log.Fatalf("unable to list machines: %s", err)
}

View file

@ -8,6 +8,8 @@ import (
"strings"
"github.com/confluentinc/bincover"
"github.com/fatih/color"
cc "github.com/ivanpirog/coloredcobra"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/cobra/doc"
@ -140,6 +142,21 @@ It is meant to allow you to manage bans, parsers/scenarios/etc, api and generall
SilenceUsage: true,
/*TBD examples*/
}
cc.Init(&cc.Config{
RootCmd: rootCmd,
Headings: cc.Yellow,
Commands: cc.Green + cc.Bold,
CmdShortDescr: cc.Cyan,
Example: cc.Italic,
ExecName: cc.Bold,
Aliases: cc.Bold + cc.Italic,
FlagsDataType: cc.White,
Flags: cc.Green,
FlagsDescr: cc.Cyan,
})
rootCmd.SetOut(color.Output)
var cmdDocGen = &cobra.Command{
Use: "doc",
Short: "Generate the documentation in `./doc/`. Directory must exist.",
@ -167,7 +184,7 @@ It is meant to allow you to manage bans, parsers/scenarios/etc, api and generall
rootCmd.PersistentFlags().StringVarP(&ConfigFilePath, "config", "c", csconfig.DefaultConfigPath("config.yaml"), "path to crowdsec config file")
rootCmd.PersistentFlags().StringVarP(&OutputFormat, "output", "o", "", "Output format: human, json, raw.")
rootCmd.PersistentFlags().StringVarP(&OutputColor, "color", "", csconfig.ColorDefault(), "Output color: yes, no, auto.")
rootCmd.PersistentFlags().StringVarP(&OutputColor, "color", "", "auto", "Output color: yes, no, auto.")
rootCmd.PersistentFlags().BoolVar(&dbg_lvl, "debug", false, "Set logging to debug.")
rootCmd.PersistentFlags().BoolVar(&nfo_lvl, "info", false, "Set logging to info.")
rootCmd.PersistentFlags().BoolVar(&wrn_lvl, "warning", false, "Set logging to warning.")

View file

@ -3,9 +3,9 @@
package main
import (
"github.com/confluentinc/bincover"
"testing"
"github.com/confluentinc/bincover"
)
func TestBincoverRunMain(t *testing.T) {

View file

@ -10,7 +10,7 @@ import (
"strings"
"time"
colorable "github.com/mattn/go-colorable"
"github.com/fatih/color"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/prom2json"
log "github.com/sirupsen/logrus"
@ -276,7 +276,7 @@ func NewMetricsCmd() *cobra.Command {
os.Exit(1)
}
err := FormatPrometheusMetrics(colorable.NewColorableStdout(), prometheusURL+"/metrics", csConfig.Cscli.Output)
err := FormatPrometheusMetrics(color.Output, prometheusURL+"/metrics", csConfig.Cscli.Output)
if err != nil {
log.Fatalf("could not fetch prometheus metrics: %s", err)
}

View file

@ -13,8 +13,8 @@ import (
"strings"
"time"
"github.com/fatih/color"
"github.com/go-openapi/strfmt"
colorable "github.com/mattn/go-colorable"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
@ -68,7 +68,7 @@ func NewNotificationsCmd() *cobra.Command {
}
if csConfig.Cscli.Output == "human" {
notificationListTable(colorable.NewColorableStdout(), ncfgs)
notificationListTable(color.Output, ncfgs)
} else if csConfig.Cscli.Output == "json" {
x, err := json.MarshalIndent(ncfgs, "", " ")
if err != nil {

View file

@ -3,7 +3,7 @@ package main
import (
"fmt"
colorable "github.com/mattn/go-colorable"
"github.com/fatih/color"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
@ -164,7 +164,7 @@ cscli parsers remove crowdsecurity/sshd-logs
cscli parser list crowdsecurity/xxx`,
DisableAutoGenTag: true,
Run: func(cmd *cobra.Command, args []string) {
ListItems(colorable.NewColorableStdout(), []string{cwhub.PARSERS}, args, false, true, all)
ListItems(color.Output, []string{cwhub.PARSERS}, args, false, true, all)
},
}
cmdParsersList.PersistentFlags().BoolVarP(&all, "all", "a", false, "List disabled items as well")

View file

@ -3,7 +3,7 @@ package main
import (
"fmt"
colorable "github.com/mattn/go-colorable"
"github.com/fatih/color"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
@ -162,7 +162,7 @@ func NewPostOverflowsCmd() *cobra.Command {
cscli postoverflows list crowdsecurity/xxx`,
DisableAutoGenTag: true,
Run: func(cmd *cobra.Command, args []string) {
ListItems(colorable.NewColorableStdout(), []string{cwhub.PARSERS_OVFLW}, args, false, true, all)
ListItems(color.Output, []string{cwhub.PARSERS_OVFLW}, args, false, true, all)
},
}
cmdPostOverflowsList.PersistentFlags().BoolVarP(&all, "all", "a", false, "List disabled items as well")

View file

@ -3,7 +3,7 @@ package main
import (
"fmt"
colorable "github.com/mattn/go-colorable"
"github.com/fatih/color"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
@ -167,7 +167,7 @@ cscli scenarios remove crowdsecurity/ssh-bf
cscli scenarios list crowdsecurity/xxx`,
DisableAutoGenTag: true,
Run: func(cmd *cobra.Command, args []string) {
ListItems(colorable.NewColorableStdout(), []string{cwhub.SCENARIOS}, args, false, true, all)
ListItems(color.Output, []string{cwhub.SCENARIOS}, args, false, true, all)
},
}
cmdScenariosList.PersistentFlags().BoolVarP(&all, "all", "a", false, "List disabled items as well")

View file

@ -4,10 +4,11 @@ import (
"fmt"
"os"
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
)
func addToExclusion(name string) error {

View file

@ -13,7 +13,7 @@ import (
"strings"
"time"
colorable "github.com/mattn/go-colorable"
"github.com/fatih/color"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/prom2json"
log "github.com/sirupsen/logrus"
@ -304,18 +304,18 @@ func ShowMetrics(hubItem *cwhub.Item) {
switch hubItem.Type {
case cwhub.PARSERS:
metrics := GetParserMetric(prometheusURL, hubItem.Name)
parserMetricsTable(colorable.NewColorableStdout(), hubItem.Name, metrics)
parserMetricsTable(color.Output, hubItem.Name, metrics)
case cwhub.SCENARIOS:
metrics := GetScenarioMetric(prometheusURL, hubItem.Name)
scenarioMetricsTable(colorable.NewColorableStdout(), hubItem.Name, metrics)
scenarioMetricsTable(color.Output, hubItem.Name, metrics)
case cwhub.COLLECTIONS:
for _, item := range hubItem.Parsers {
metrics := GetParserMetric(prometheusURL, item)
parserMetricsTable(colorable.NewColorableStdout(), item, metrics)
parserMetricsTable(color.Output, item, metrics)
}
for _, item := range hubItem.Scenarios {
metrics := GetScenarioMetric(prometheusURL, item)
scenarioMetricsTable(colorable.NewColorableStdout(), item, metrics)
scenarioMetricsTable(color.Output, item, metrics)
}
for _, item := range hubItem.Collections {
hubItem = cwhub.GetItem(cwhub.COLLECTIONS, item)

1
go.mod
View file

@ -116,6 +116,7 @@ require (
github.com/huandu/xstrings v1.3.2 // indirect
github.com/imdario/mergo v0.3.12 // indirect
github.com/inconshreveable/mousetrap v1.0.1 // indirect
github.com/ivanpirog/coloredcobra v1.0.1 // indirect
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
github.com/jackc/pgconn v1.10.1 // indirect
github.com/jackc/pgio v1.0.0 // indirect

4
go.sum
View file

@ -135,6 +135,7 @@ github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7
github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf h1:iW4rZ826su+pqaw19uhpSCzhj44qo35pNgKFGqzDKkU=
github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w=
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/creachadair/staticfile v0.1.3/go.mod h1:a3qySzCIXEprDGxk6tSxSI+dBBdLzqeBOMhZ+o2d3pM=
@ -438,6 +439,8 @@ github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/inconshreveable/mousetrap v1.0.1 h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7Pgzkat/bFNc=
github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/ivanpirog/coloredcobra v1.0.1 h1:aURSdEmlR90/tSiWS0dMjdwOvCVUeYLfltLfbgNxrN4=
github.com/ivanpirog/coloredcobra v1.0.1/go.mod h1:iho4nEKcnwZFiniGSdcgdvRgZNjxm+h20acv8vqmN6Q=
github.com/jackc/chunkreader v1.0.0/go.mod h1:RT6O25fNZIuasFJRyZ4R/Y2BbhasbmZXF9QQ7T3kePo=
github.com/jackc/chunkreader/v2 v2.0.0/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk=
github.com/jackc/chunkreader/v2 v2.0.1 h1:i+RDz65UE+mmpjTfyz0MoVTnzeYxroil2G82ki7MGG8=
@ -721,6 +724,7 @@ github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic
github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng=
github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ=
github.com/spf13/cobra v1.4.0/go.mod h1:Wo4iy3BUC+X2Fybo0PDqwJIv3dNRiZLHQymsfxlB84g=
github.com/spf13/cobra v1.5.0 h1:X+jTBEBqF0bHN+9cSMgmfuvv2VHJ9ezmFNf9Y/XstYU=
github.com/spf13/cobra v1.5.0/go.mod h1:dWXEIy2H428czQCjInthrTRUg7yKbok+2Qi/yBIJoUM=
github.com/spf13/pflag v1.0.2/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=

View file

@ -95,7 +95,7 @@ func NewDefaultConfig() *Config {
cscliCfg := CscliCfg{
Output: "human",
Color: ColorDefault(),
Color: "auto",
}
apiCfg := APICfg{

View file

@ -1,9 +1,5 @@
package csconfig
import (
"runtime"
)
/*cscli specific config, such as hub directory*/
type CscliCfg struct {
Output string `yaml:"output,omitempty"`
@ -19,13 +15,6 @@ type CscliCfg struct {
PrometheusUrl string `yaml:"prometheus_uri"`
}
func ColorDefault() string {
if runtime.GOOS == "windows" {
return "no"
}
return "auto"
}
func (c *Config) LoadCSCLI() error {
if c.Cscli == nil {
c.Cscli = &CscliCfg{}