/commands/helpers.go

https://gitlab.com/gohugo/hugo · Go · 79 lines · 46 code · 15 blank · 18 comment · 2 complexity · 8615a80dfd3d154c1d6ba2bfa569581c MD5 · raw file

  1. // Copyright 2018 The Hugo Authors. All rights reserved.
  2. //
  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. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. // Package commands defines and implements command-line commands and flags
  14. // used by Hugo. Commands and flags are implemented using Cobra.
  15. package commands
  16. import (
  17. "fmt"
  18. "regexp"
  19. "github.com/gohugoio/hugo/config"
  20. "github.com/spf13/cobra"
  21. )
  22. const (
  23. ansiEsc = "\u001B"
  24. clearLine = "\r\033[K"
  25. hideCursor = ansiEsc + "[?25l"
  26. showCursor = ansiEsc + "[?25h"
  27. )
  28. type flagsToConfigHandler interface {
  29. flagsToConfig(cfg config.Provider)
  30. }
  31. type cmder interface {
  32. flagsToConfigHandler
  33. getCommand() *cobra.Command
  34. }
  35. // commandError is an error used to signal different error situations in command handling.
  36. type commandError struct {
  37. s string
  38. userError bool
  39. }
  40. func (c commandError) Error() string {
  41. return c.s
  42. }
  43. func (c commandError) isUserError() bool {
  44. return c.userError
  45. }
  46. func newUserError(a ...any) commandError {
  47. return commandError{s: fmt.Sprintln(a...), userError: true}
  48. }
  49. func newSystemError(a ...any) commandError {
  50. return commandError{s: fmt.Sprintln(a...), userError: false}
  51. }
  52. func newSystemErrorF(format string, a ...any) commandError {
  53. return commandError{s: fmt.Sprintf(format, a...), userError: false}
  54. }
  55. // Catch some of the obvious user errors from Cobra.
  56. // We don't want to show the usage message for every error.
  57. // The below may be to generic. Time will show.
  58. var userErrorRegexp = regexp.MustCompile("unknown flag")
  59. func isUserError(err error) bool {
  60. if cErr, ok := err.(commandError); ok && cErr.isUserError() {
  61. return true
  62. }
  63. return userErrorRegexp.MatchString(err.Error())
  64. }