report.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. Copyright 2016 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package system
  14. import (
  15. "fmt"
  16. "io"
  17. "os"
  18. "github.com/pkg/errors"
  19. )
  20. // ValidationResultType is type of the validation result. Different validation results
  21. // corresponds to different colors.
  22. type ValidationResultType int32
  23. const (
  24. good ValidationResultType = iota
  25. bad
  26. warn
  27. )
  28. // color is the color of the message.
  29. type color int32
  30. const (
  31. red color = 31
  32. green color = 32
  33. yellow color = 33
  34. white color = 37
  35. )
  36. func colorize(s string, c color) string {
  37. return fmt.Sprintf("\033[0;%dm%s\033[0m", c, s)
  38. }
  39. // StreamReporter is the default reporter for the system verification test.
  40. type StreamReporter struct {
  41. // The stream that this reporter is writing to
  42. WriteStream io.Writer
  43. }
  44. // Report reports validation result in different color depending on the result type.
  45. func (dr *StreamReporter) Report(key, value string, resultType ValidationResultType) error {
  46. var c color
  47. switch resultType {
  48. case good:
  49. c = green
  50. case bad:
  51. c = red
  52. case warn:
  53. c = yellow
  54. default:
  55. c = white
  56. }
  57. if dr.WriteStream == nil {
  58. return errors.New("WriteStream has to be defined for this reporter")
  59. }
  60. fmt.Fprintf(dr.WriteStream, "%s: %s\n", colorize(key, white), colorize(value, c))
  61. return nil
  62. }
  63. // DefaultReporter is the default Reporter
  64. var DefaultReporter = &StreamReporter{
  65. WriteStream: os.Stdout,
  66. }