Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add --force-color flag to zed validate #435

Merged
merged 7 commits into from
Nov 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/lint.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ jobs:
format: "table"
exit-code: "1"
severity: "CRITICAL,HIGH,MEDIUM"
env:
TRIVY_DB_REPOSITORY: "public.ecr.aws/aquasecurity/trivy-db"
TRIVY_JAVA_DB_REPOSITORY: "public.ecr.aws/aquasecurity/trivy-java-db"

trivy-image:
name: "Analyze Release Image with Trivy"
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ require (
github.com/jzelinskie/stringz v0.0.3
github.com/mattn/go-isatty v0.0.20
github.com/mitchellh/go-homedir v1.1.0
github.com/muesli/termenv v0.15.2
github.com/olekukonko/tablewriter v0.0.5
github.com/rodaine/table v1.3.0
github.com/rs/zerolog v1.33.0
Expand Down Expand Up @@ -179,7 +180,6 @@ require (
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/mostynb/go-grpc-compression v1.2.3 // indirect
github.com/mtibben/percent v0.2.1 // indirect
github.com/muesli/termenv v0.15.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/ngrok/sqlmw v0.0.0-20220520173518-97c9c04efc79 // indirect
github.com/onsi/ginkgo/v2 v2.20.2 // indirect
Expand Down
74 changes: 48 additions & 26 deletions internal/cmd/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import (
"github.com/authzed/spicedb/pkg/spiceerrors"
"github.com/authzed/spicedb/pkg/validationfile"
"github.com/charmbracelet/lipgloss"
"github.com/jzelinskie/cobrautil/v2"
"github.com/muesli/termenv"

"github.com/authzed/zed/internal/commands"
"github.com/authzed/zed/internal/console"
Expand All @@ -24,21 +26,28 @@ import (
)

var (
success = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("10")).Render("Success!")
complete = lipgloss.NewStyle().Bold(true).Render("complete")
errorPrefix = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("9")).Render("error: ")
warningPrefix = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("3")).Render("warning: ")
errorMessageStyle = lipgloss.NewStyle().Bold(true).Width(80)
linePrefixStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("12"))
highlightedSourceStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("9"))
highlightedLineStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("9"))
codeStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("8"))
highlightedCodeStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("15"))
traceStyle = lipgloss.NewStyle().Bold(true)
// NOTE: these need to be set *after* the renderer has been set, otherwise
// the forceColor setting can't work, hence the thunking.
success = func() string {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what's the cost of initializing this each time? alternatively, these could be left as uninitialized vars, and initialize them after we've checked the flag

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought about that, but that spreads the definitions around the file, and some of the definitions are used by multiple functions. I don't think it's particularly expensive, though that isn't because I've profiled it.

return lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("10")).Render("Success!")
}
complete = func() string { return lipgloss.NewStyle().Bold(true).Render("complete") }
errorPrefix = func() string { return lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("9")).Render("error: ") }
warningPrefix = func() string {
return lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("3")).Render("warning: ")
}
errorMessageStyle = func() lipgloss.Style { return lipgloss.NewStyle().Bold(true).Width(80) }
linePrefixStyle = func() lipgloss.Style { return lipgloss.NewStyle().Foreground(lipgloss.Color("12")) }
highlightedSourceStyle = func() lipgloss.Style { return lipgloss.NewStyle().Foreground(lipgloss.Color("9")) }
highlightedLineStyle = func() lipgloss.Style { return lipgloss.NewStyle().Foreground(lipgloss.Color("9")) }
codeStyle = func() lipgloss.Style { return lipgloss.NewStyle().Foreground(lipgloss.Color("8")) }
highlightedCodeStyle = func() lipgloss.Style { return lipgloss.NewStyle().Foreground(lipgloss.Color("15")) }
traceStyle = func() lipgloss.Style { return lipgloss.NewStyle().Bold(true) }
)

func registerValidateCmd(rootCmd *cobra.Command) {
rootCmd.AddCommand(validateCmd)
func registerValidateCmd(cmd *cobra.Command) {
validateCmd.Flags().Bool("force-color", false, "force color code output even in non-tty environments")
cmd.AddCommand(validateCmd)
}

var validateCmd = &cobra.Command{
Expand All @@ -64,9 +73,22 @@ var validateCmd = &cobra.Command{
zed validate https://localhost:8443/download`,
Args: cobra.ExactArgs(1),
ValidArgsFunction: commands.FileExtensionCompletions("zed", "yaml", "zaml"),
PreRunE: validatePreRunE,
RunE: validateCmdFunc,
}

func validatePreRunE(cmd *cobra.Command, _ []string) error {
// Override lipgloss's autodetection of whether it's in a terminal environment
// and display things in color anyway. This can be nice in CI environments that
// support it.
setForceColor := cobrautil.MustGetBool(cmd, "force-color")
if setForceColor {
lipgloss.SetColorProfile(termenv.ANSI256)
}

return nil
}

func validateCmdFunc(cmd *cobra.Command, args []string) error {
// Parse the URL of the validation document to import.
u, err := url.Parse(args[0])
Expand Down Expand Up @@ -139,14 +161,14 @@ func validateCmdFunc(cmd *cobra.Command, args []string) error {

if len(warnings) > 0 {
for _, warning := range warnings {
console.Printf("%s%s\n", warningPrefix, warning.Message)
console.Printf("%s%s\n", warningPrefix(), warning.Message)
outputForLine(validateContents, uint64(warning.Line), warning.SourceCode, uint64(warning.Column)) // warning.LineNumber is 1-indexed
console.Printf("\n")
}

console.Print(complete)
console.Print(complete())
} else {
console.Print(success)
console.Print(success())
}

console.Printf(" - %d relationships loaded, %d assertions run, %d expected relations validated\n",
Expand All @@ -158,7 +180,7 @@ func validateCmdFunc(cmd *cobra.Command, args []string) error {
}

func ouputErrorWithSource(validateContents []byte, errWithSource spiceerrors.ErrorWithSource) {
console.Printf("%s%s\n", errorPrefix, errorMessageStyle.Render(errWithSource.Error()))
console.Printf("%s%s\n", errorPrefix(), errorMessageStyle().Render(errWithSource.Error()))
outputForLine(validateContents, errWithSource.LineNumber, errWithSource.SourceCodeString, 0) // errWithSource.LineNumber is 1-indexed
os.Exit(1)
}
Expand Down Expand Up @@ -193,7 +215,7 @@ func outputDeveloperErrorsWithLineOffset(validateContents []byte, devErrors []*d
}

func outputDeveloperError(devError *devinterface.DeveloperError, lines []string, lineOffset int) {
console.Printf("%s %s\n", errorPrefix, errorMessageStyle.Render(devError.Message))
console.Printf("%s %s\n", errorPrefix(), errorMessageStyle().Render(devError.Message))
errorLineNumber := int(devError.Line) - 1 + lineOffset // devError.Line is 1-indexed
for i := errorLineNumber - 3; i < errorLineNumber+3; i++ {
if i == errorLineNumber {
Expand All @@ -204,7 +226,7 @@ func outputDeveloperError(devError *devinterface.DeveloperError, lines []string,
}

if devError.CheckResolvedDebugInformation != nil && devError.CheckResolvedDebugInformation.Check != nil {
console.Printf("\n %s\n", traceStyle.Render("Explanation:"))
console.Printf("\n %s\n", traceStyle().Render("Explanation:"))
tp := printers.NewTreePrinter()
printers.DisplayCheckTrace(devError.CheckResolvedDebugInformation.Check, tp, true)
tp.PrintIndented()
Expand Down Expand Up @@ -261,23 +283,23 @@ func renderLine(lines []string, index int, highlight string, highlightLineIndex
lineNumberSpacer := strings.Repeat(" ", lineNumberLength-len(lineNumberStr))

if highlightColumnIndex < 0 {
console.Printf(" %s%s %s %s\n", lineNumberSpacer, lineNumberStyle.Render(lineNumberStr), lineDelimiter, lineContentsStyle.Render(lineContents))
console.Printf(" %s%s %s %s\n", lineNumberSpacer, lineNumberStyle().Render(lineNumberStr), lineDelimiter, lineContentsStyle().Render(lineContents))
} else {
console.Printf(" %s%s %s %s%s%s\n",
lineNumberSpacer,
lineNumberStyle.Render(lineNumberStr),
lineNumberStyle().Render(lineNumberStr),
lineDelimiter,
lineContentsStyle.Render(lineContents[0:highlightColumnIndex]),
highlightedSourceStyle.Render(highlight),
lineContentsStyle.Render(lineContents[highlightColumnIndex+len(highlight):]),
lineContentsStyle().Render(lineContents[0:highlightColumnIndex]),
highlightedSourceStyle().Render(highlight),
lineContentsStyle().Render(lineContents[highlightColumnIndex+len(highlight):]),
)

console.Printf(" %s %s %s%s%s\n",
noNumberSpaces,
lineDelimiter,
strings.Repeat(" ", highlightColumnIndex),
highlightedSourceStyle.Render("^"),
highlightedSourceStyle.Render(strings.Repeat("~", highlightLength)),
highlightedSourceStyle().Render("^"),
highlightedSourceStyle().Render(strings.Repeat("~", highlightLength)),
)
}
}
Loading