Skip to content

Commit

Permalink
Fix up UI messages (#2629)
Browse files Browse the repository at this point in the history
* Fix up UI messages

Signed-off-by: Zachary Newman <zjn@chainguard.dev>

* Rename Warn/Info to Warnf/Infof

Signed-off-by: Zachary Newman <zjn@chainguard.dev>

Signed-off-by: Zachary Newman <zjn@chainguard.dev>
  • Loading branch information
znewman01 authored Jan 24, 2023
1 parent e4453c2 commit fb74f73
Show file tree
Hide file tree
Showing 10 changed files with 44 additions and 47 deletions.
10 changes: 5 additions & 5 deletions cmd/cosign/cli/clean.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func Clean() *cobra.Command {

func CleanCmd(ctx context.Context, regOpts options.RegistryOptions, cleanType options.CleanType, imageRef string, force bool) error {
if !force {
ui.Warn(ctx, prompt(cleanType))
ui.Warnf(ctx, prompt(cleanType))
if err := ui.ConfirmContinue(ctx); err != nil {
return err
}
Expand Down Expand Up @@ -114,13 +114,13 @@ func CleanCmd(ctx context.Context, regOpts options.RegistryOptions, cleanType op
func prompt(cleanType options.CleanType) string {
switch cleanType {
case options.CleanTypeSignature:
return "WARNING: this will remove all signatures from the image"
return "this will remove all signatures from the image"
case options.CleanTypeSbom:
return "WARNING: this will remove all SBOMs from the image"
return "this will remove all SBOMs from the image"
case options.CleanTypeAttestation:
return "WARNING: this will remove all attestations from the image"
return "this will remove all attestations from the image"
case options.CleanTypeAll:
return "WARNING: this will remove all signatures, SBOMs and attestations from the image"
return "this will remove all signatures, SBOMs and attestations from the image"
}
panic("invalid CleanType value")
}
4 changes: 2 additions & 2 deletions cmd/cosign/cli/fulcio/fulcio.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,8 +162,8 @@ func NewSigner(ctx context.Context, ko options.KeyOpts) (*Signer, error) {
default:
var statementErr error
privacy.StatementOnce.Do(func() {
ui.Info(ctx, privacy.Statement)
ui.Info(ctx, privacy.StatementConfirmation)
ui.Infof(ctx, privacy.Statement)
ui.Infof(ctx, privacy.StatementConfirmation)
if !ko.SkipConfirmation {
if err := ui.ConfirmContinue(ctx); err != nil {
statementErr = err
Expand Down
2 changes: 1 addition & 1 deletion cmd/cosign/cli/generate/generate_key_pair.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ func GenerateKeyPairCmd(ctx context.Context, kmsVal string, outputKeyPrefixVal s
}

if fileExists {
ui.Warn(ctx, "File %s already exists. Overwrite?", privateKeyFileName)
ui.Warnf(ctx, "File %s already exists. Overwrite?", privateKeyFileName)
if err := ui.ConfirmContinue(ctx); err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/cosign/cli/importkeypair/import_key_pair.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func ImportKeyPairCmd(ctx context.Context, keyVal string, outputKeyPrefixVal str
}

if fileExists {
ui.Warn(ctx, "File %s already exists. Overwrite?", privateKeyFileName)
ui.Warnf(ctx, "File %s already exists. Overwrite?", privateKeyFileName)
if err := ui.ConfirmContinue(ctx); err != nil {
return err
}
Expand Down
33 changes: 15 additions & 18 deletions cmd/cosign/cli/sign/sign.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ func ShouldUploadToTlog(ctx context.Context, ko options.KeyOpts, ref name.Refere
var statementErr error
if upload {
privacy.StatementOnce.Do(func() {
ui.Info(ctx, privacy.Statement)
ui.Info(ctx, privacy.StatementConfirmation)
ui.Infof(ctx, privacy.Statement)
ui.Infof(ctx, privacy.StatementConfirmation)
if !ko.SkipConfirmation {
if err := ui.ConfirmContinue(ctx); err != nil {
statementErr = err
Expand Down Expand Up @@ -102,12 +102,9 @@ func shouldUploadToTlog(ctx context.Context, ko options.KeyOpts, ref name.Refere

// Check if the image is public (no auth in Get)
if _, err := remote.Get(ref, remote.WithContext(ctx)); err != nil {
ui.Warn(ctx, "%q appears to be a private repository, please confirm uploading to the transparency log at %q", ref.Context().String(), ko.RekorURL)
var errPromptDeclined *ui.ErrPromptDeclined
if err := ui.ConfirmContinue(ctx); errors.As(err, &errPromptDeclined) {
ui.Info(ctx, "not uploading to transparency log")
} else if err != nil {
ui.Warn(ctx, "skipping transparency log upload (use --yes to skip confirmation): %v\n", err)
ui.Warnf(ctx, "%q appears to be a private repository, please confirm uploading to the transparency log at %q", ref.Context().String(), ko.RekorURL)
if ui.ConfirmContinue(ctx) != nil {
ui.Infof(ctx, "not uploading to transparency log")
return false
}
}
Expand All @@ -132,7 +129,7 @@ func ParseOCIReference(ctx context.Context, refStr string, opts ...name.Option)
}
if _, ok := ref.(name.Digest); !ok {
msg := fmt.Sprintf(TagReferenceMessage, refStr)
ui.Warn(ctx, msg)
ui.Warnf(ctx, msg)
}
return ref, nil
}
Expand All @@ -155,7 +152,7 @@ func SignCmd(ro *options.RootOptions, ko options.KeyOpts, signOpts options.SignO

var staticPayload []byte
if signOpts.PayloadPath != "" {
ui.Info(ctx, "Using payload from:", signOpts.PayloadPath)
ui.Infof(ctx, "Using payload from: %s", signOpts.PayloadPath)
staticPayload, err = os.ReadFile(filepath.Clean(signOpts.PayloadPath))
if err != nil {
return fmt.Errorf("payload from file: %w", err)
Expand Down Expand Up @@ -295,7 +292,7 @@ func signDigest(ctx context.Context, digest name.Digest, payload []byte, ko opti
return fmt.Errorf("create certificate file: %w", err)
}
// TODO: maybe accept a --b64 flag as well?
ui.Info(ctx, "Certificate wrote in the file %s", outputCertificate)
ui.Infof(ctx, "Certificate wrote in the file %s", outputCertificate)
}

if !upload {
Expand All @@ -317,9 +314,9 @@ func signDigest(ctx context.Context, digest name.Digest, payload []byte, ko opti
// Check if we are overriding the signatures repository location
repo, _ := ociremote.GetEnvTargetRepository()
if repo.RepositoryStr() == "" {
ui.Info(ctx, "Pushing signature to:", digest.Repository)
ui.Infof(ctx, "Pushing signature to: %s", digest.Repository)
} else {
ui.Info(ctx, "Pushing signature to:", repo.RepositoryStr())
ui.Infof(ctx, "Pushing signature to: %s", repo.RepositoryStr())
}

// Publish the signatures associated with this entity
Expand Down Expand Up @@ -348,7 +345,7 @@ func signerFromSecurityKey(ctx context.Context, keySlot string) (*SignerVerifier
certFromPIV, err := sk.Certificate()
var pemBytes []byte
if err != nil {
ui.Warn(ctx, "no x509 certificate retrieved from the PIV token")
ui.Warnf(ctx, "no x509 certificate retrieved from the PIV token")
} else {
pemBytes, err = cryptoutils.MarshalCertificateToPEM(certFromPIV)
if err != nil {
Expand Down Expand Up @@ -384,7 +381,7 @@ func signerFromKeyRef(ctx context.Context, certPath, certChainPath, keyRef strin
certSigner.close = pkcs11Key.Close

if certFromPKCS11 == nil {
ui.Warn(ctx, "no x509 certificate retrieved from the PKCS11 token")
ui.Warnf(ctx, "no x509 certificate retrieved from the PKCS11 token")
} else {
pemBytes, err := cryptoutils.MarshalCertificateToPEM(certFromPKCS11)
if err != nil {
Expand Down Expand Up @@ -437,7 +434,7 @@ func signerFromKeyRef(ctx context.Context, certPath, certChainPath, keyRef strin
return nil, fmt.Errorf("marshaling certificate to PEM: %w", err)
}
if certSigner.Cert != nil {
ui.Warn(ctx, "overriding x509 certificate retrieved from the PKCS11 token")
ui.Warnf(ctx, "overriding x509 certificate retrieved from the PKCS11 token")
}
leafCert = parsedCert
certSigner.Cert = pemBytes
Expand Down Expand Up @@ -527,7 +524,7 @@ func SignerFromKeyOpts(ctx context.Context, certPath string, certChainPath strin
}

// Default Keyless!
ui.Info(ctx, "Generating ephemeral keys...")
ui.Infof(ctx, "Generating ephemeral keys...")
return keylessSigner(ctx, ko)
}

Expand All @@ -546,7 +543,7 @@ func (c *SignerVerifier) Close() {

func (c *SignerVerifier) Bytes(ctx context.Context) ([]byte, error) {
if c.Cert != nil {
ui.Info(ctx, "using ephemeral certificate:\n%s", string(c.Cert))
ui.Infof(ctx, "using ephemeral certificate:\n%s", string(c.Cert))
return c.Cert, nil
}

Expand Down
4 changes: 2 additions & 2 deletions cmd/cosign/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func main() {
if strings.HasPrefix(arg, "--") && len(arg) == 3 {
// Handle --o, convert to -o
newArg := fmt.Sprintf("-%c", arg[2])
ui.Warn(ctx, "the flag %s is deprecated and will be removed in a future release. Please use the flag %s.", arg, newArg)
ui.Warnf(ctx, "the flag %s is deprecated and will be removed in a future release. Please use the flag %s.", arg, newArg)
os.Args[i] = newArg
} else if strings.HasPrefix(arg, "-") && len(arg) > 1 {
// Handle -output, convert to --output
Expand All @@ -51,7 +51,7 @@ func main() {
newArg = "version"
newArgType = "subcommand"
}
ui.Warn(ctx, "the %s flag is deprecated and will be removed in a future release. "+
ui.Warnf(ctx, "the %s flag is deprecated and will be removed in a future release. "+
"Please use the %s %s instead.",
arg, newArg, newArgType,
)
Expand Down
16 changes: 8 additions & 8 deletions internal/ui/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,24 @@ import (
"fmt"
)

func (w *Env) info(msg string, a ...any) {
func (w *Env) infof(msg string, a ...any) {
msg = fmt.Sprintf(msg, a...)
fmt.Fprintln(w.Stderr, msg)
}

// Info logs an informational message. It works like fmt.Printf, except that it
// Infof logs an informational message. It works like fmt.Printf, except that it
// always has a trailing newline.
func Info(ctx context.Context, msg string, a ...any) {
getEnv(ctx).info(msg, a...)
func Infof(ctx context.Context, msg string, a ...any) {
getEnv(ctx).infof(msg, a...)
}

func (w *Env) warn(msg string, a ...any) {
func (w *Env) warnf(msg string, a ...any) {
msg = fmt.Sprintf(msg, a...)
fmt.Fprintf(w.Stderr, "WARNING: %s\n", msg)
}

// Warn logs a warning message (prefixed by "WARNING:"). It works like
// Warnf logs a warning message (prefixed by "WARNING:"). It works like
// fmt.Printf, except that it always has a trailing newline.
func Warn(ctx context.Context, msg string, a ...any) {
getEnv(ctx).warn(msg, a...)
func Warnf(ctx context.Context, msg string, a ...any) {
getEnv(ctx).warnf(msg, a...)
}
8 changes: 4 additions & 4 deletions internal/ui/log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,29 +28,29 @@ type testCase struct {
expected string
}

func TestInfo(t *testing.T) {
func TestInfof(t *testing.T) {
cases := []testCase{
{"basic", "foo", nil, "foo\n"},
{"multiline", "foo\nbar", nil, "foo\nbar\n"},
{"fmt", "foo: %v", []any{"bar"}, "foo: bar\n"},
}
for _, tc := range cases {
stderr := ui.RunWithTestCtx(func(ctx context.Context, write ui.WriteFunc) {
ui.Info(ctx, tc.input, tc.args...)
ui.Infof(ctx, tc.input, tc.args...)
})
assert.Equal(t, tc.expected, stderr, "Bad output to STDERR")
}
}

func TestWarn(t *testing.T) {
func TestWarnf(t *testing.T) {
cases := []testCase{
{"basic", "foo", nil, "WARNING: foo\n"},
{"multiline", "foo\nbar", nil, "WARNING: foo\nbar\n"},
{"fmt", "bar: %v", []any{"baz"}, "WARNING: bar: baz\n"},
}
for _, tc := range cases {
stderr := ui.RunWithTestCtx(func(ctx context.Context, write ui.WriteFunc) {
ui.Warn(ctx, tc.input, tc.args...)
ui.Warnf(ctx, tc.input, tc.args...)
})
assert.Equal(t, tc.expected, stderr, "Bad output to STDERR")
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/cosign/tlog.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ func doUpload(ctx context.Context, rekorClient *client.Rekor, pe models.Proposed
// Here, we display the proof and succeed.
var existsErr *entries.CreateLogEntryConflict
if errors.As(err, &existsErr) {
ui.Info(ctx, "Signature already exists. Displaying proof")
ui.Infof(ctx, "Signature already exists. Displaying proof")
uriSplit := strings.Split(existsErr.Location.String(), "/")
uuid := uriSplit[len(uriSplit)-1]
e, err := GetTlogEntry(ctx, rekorClient, uuid)
Expand Down Expand Up @@ -461,7 +461,7 @@ func VerifyTLogEntryOffline(ctx context.Context, e *models.LogEntryAnon, rekorPu
return fmt.Errorf("verifying signedEntryTimestamp: %w", err)
}
if pubKey.Status != tuf.Active {
ui.Info(ctx, "Successfully verified Rekor entry using an expired verification key")
ui.Infof(ctx, "Successfully verified Rekor entry using an expired verification key")
}
return nil
}
Expand Down
8 changes: 4 additions & 4 deletions pkg/policy/eval.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ func EvaluatePolicyAgainstJSON(ctx context.Context, name, policyType string, pol

// evaluateCue evaluates a cue policy `evaluator` against `attestation`
func evaluateCue(ctx context.Context, attestation []byte, evaluator string) error {
ui.Info(ctx, "Evaluating attestation: %s", string(attestation))
ui.Info(ctx, "Evaluator: %s", evaluator)
ui.Infof(ctx, "Evaluating attestation: %s", string(attestation))
ui.Infof(ctx, "Evaluator: %s", evaluator)

cueCtx := cuecontext.New()
cueEvaluator := cueCtx.CompileString(evaluator)
Expand All @@ -75,8 +75,8 @@ func evaluateCue(ctx context.Context, attestation []byte, evaluator string) erro

// evaluateRego evaluates a rego policy `evaluator` against `attestation`
func evaluateRego(ctx context.Context, attestation []byte, evaluator string) (warnings error, errors error) {
ui.Info(ctx, "Evaluating attestation: %s", string(attestation))
ui.Info(ctx, "Evaluating evaluator: %s", evaluator)
ui.Infof(ctx, "Evaluating attestation: %s", string(attestation))
ui.Infof(ctx, "Evaluating evaluator: %s", evaluator)

return rego.ValidateJSONWithModuleInput(attestation, evaluator)
}

0 comments on commit fb74f73

Please sign in to comment.