helper.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /*
  2. * ECAL
  3. *
  4. * Copyright 2020 Matthias Ladkau. All rights reserved.
  5. *
  6. * This Source Code Form is subject to the terms of the MIT
  7. * License, If a copy of the MIT License was not distributed with this
  8. * file, You can obtain one at https://opensource.org/licenses/MIT.
  9. */
  10. package tool
  11. import (
  12. "fmt"
  13. "io"
  14. "os"
  15. "regexp"
  16. "strings"
  17. "devt.de/krotik/common/stringutil"
  18. )
  19. /*
  20. osArgs is a local copy of os.Args (used for unit tests)
  21. */
  22. var osArgs = os.Args
  23. /*
  24. osStderr is a local copy of os.Stderr (used for unit tests)
  25. */
  26. var osStderr io.Writer = os.Stderr
  27. /*
  28. osExit is a local variable pointing to os.Exit (used for unit tests)
  29. */
  30. var osExit func(int) = os.Exit
  31. /*
  32. CLIInputHandler is a handler object for CLI input.
  33. */
  34. type CLIInputHandler interface {
  35. /*
  36. CanHandle checks if a given string can be handled by this handler.
  37. */
  38. CanHandle(s string) bool
  39. /*
  40. Handle handles a given input string.
  41. */
  42. Handle(ot OutputTerminal, input string)
  43. }
  44. /*
  45. OutputTerminal is a generic output terminal which can write strings.
  46. */
  47. type OutputTerminal interface {
  48. /*
  49. WriteString write a string on this terminal.
  50. */
  51. WriteString(s string)
  52. }
  53. /*
  54. matchesFulltextSearch checks if a given text matches a given glob expression. Returns
  55. true if an error occurs.
  56. */
  57. func matchesFulltextSearch(ot OutputTerminal, text string, glob string) bool {
  58. var res bool
  59. re, err := stringutil.GlobToRegex(glob)
  60. if err == nil {
  61. res, err = regexp.MatchString(re, text)
  62. }
  63. if err != nil {
  64. ot.WriteString(fmt.Sprintln("Invalid search expression:", err.Error()))
  65. res = true
  66. }
  67. return res
  68. }
  69. /*
  70. fillTableRow fills a table row of a display table.
  71. */
  72. func fillTableRow(tabData []string, key string, value string) []string {
  73. tabData = append(tabData, key)
  74. valSplit := stringutil.ChunkSplit(value, 80, true)
  75. tabData = append(tabData, strings.TrimSpace(valSplit[0]))
  76. for _, valPart := range valSplit[1:] {
  77. tabData = append(tabData, "")
  78. tabData = append(tabData, strings.TrimSpace(valPart))
  79. }
  80. // Insert empty rows to ease reading
  81. tabData = append(tabData, "")
  82. tabData = append(tabData, "")
  83. return tabData
  84. }