ansi.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. Copyright 2024 Docker Compose CLI 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 formatter
  14. import (
  15. "fmt"
  16. "github.com/acarl005/stripansi"
  17. )
  18. var disableAnsi bool
  19. func ansi(code string) string {
  20. return fmt.Sprintf("\033%s", code)
  21. }
  22. func SaveCursor() {
  23. if disableAnsi {
  24. return
  25. }
  26. fmt.Print(ansi("7"))
  27. }
  28. func RestoreCursor() {
  29. if disableAnsi {
  30. return
  31. }
  32. fmt.Print(ansi("8"))
  33. }
  34. func HideCursor() {
  35. if disableAnsi {
  36. return
  37. }
  38. fmt.Print(ansi("[?25l"))
  39. }
  40. func ShowCursor() {
  41. if disableAnsi {
  42. return
  43. }
  44. fmt.Print(ansi("[?25h"))
  45. }
  46. func MoveCursor(y, x int) {
  47. if disableAnsi {
  48. return
  49. }
  50. fmt.Print(ansi(fmt.Sprintf("[%d;%dH", y, x)))
  51. }
  52. func MoveCursorX(pos int) {
  53. if disableAnsi {
  54. return
  55. }
  56. fmt.Print(ansi(fmt.Sprintf("[%dG", pos)))
  57. }
  58. func ClearLine() {
  59. if disableAnsi {
  60. return
  61. }
  62. // Does not move cursor from its current position
  63. fmt.Print(ansi("[2K"))
  64. }
  65. func MoveCursorUp(lines int) {
  66. if disableAnsi {
  67. return
  68. }
  69. // Does not add new lines
  70. fmt.Print(ansi(fmt.Sprintf("[%dA", lines)))
  71. }
  72. func MoveCursorDown(lines int) {
  73. if disableAnsi {
  74. return
  75. }
  76. // Does not add new lines
  77. fmt.Print(ansi(fmt.Sprintf("[%dB", lines)))
  78. }
  79. func NewLine() {
  80. // Like \n
  81. fmt.Print("\012")
  82. }
  83. func lenAnsi(s string) int {
  84. // len has into consideration ansi codes, if we want
  85. // the len of the actual len(string) we need to strip
  86. // all ansi codes
  87. return len(stripansi.Strip(s))
  88. }