ansi.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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 showCursor() {
  35. if disableAnsi {
  36. return
  37. }
  38. fmt.Print(ansi("[?25h"))
  39. }
  40. func moveCursor(y, x int) {
  41. if disableAnsi {
  42. return
  43. }
  44. fmt.Print(ansi(fmt.Sprintf("[%d;%dH", y, x)))
  45. }
  46. func carriageReturn() {
  47. if disableAnsi {
  48. return
  49. }
  50. fmt.Print(ansi(fmt.Sprintf("[%dG", 0)))
  51. }
  52. func clearLine() {
  53. if disableAnsi {
  54. return
  55. }
  56. // Does not move cursor from its current position
  57. fmt.Print(ansi("[2K"))
  58. }
  59. func moveCursorUp(lines int) {
  60. if disableAnsi {
  61. return
  62. }
  63. // Does not add new lines
  64. fmt.Print(ansi(fmt.Sprintf("[%dA", lines)))
  65. }
  66. func moveCursorDown(lines int) {
  67. if disableAnsi {
  68. return
  69. }
  70. // Does not add new lines
  71. fmt.Print(ansi(fmt.Sprintf("[%dB", lines)))
  72. }
  73. func newLine() {
  74. // Like \n
  75. fmt.Print("\012")
  76. }
  77. func lenAnsi(s string) int {
  78. // len has into consideration ansi codes, if we want
  79. // the len of the actual len(string) we need to strip
  80. // all ansi codes
  81. return len(stripansi.Strip(s))
  82. }