~poldi1405/go-ansi

6db2a890f26cf3133be1fed40c946ed5964a8ef3 — Moritz Poldrack 2 months ago 38df6d1
updated length to work with links and notifications
2 files changed, 61 insertions(+), 1 deletions(-)

M length.go
A length_test.go
M length.go => length.go +1 -1
@@ 6,6 6,6 @@ import (
)

func GetLengthWithoutCodes(content string) int {
	var re = regexp.MustCompile(`(?m)\x1b\[([\d;]+m|[\d;]+(H|A|B|C|D|J|K|S|T)|s|u)`)
	re := regexp.MustCompile(`(?m)\x1b(\[([\d;]+m|[\d;]+(H|A|B|C|D|J|K|S|T)|s|u)|\](8;;[^\x1b]*\x1b\\|777;notify;[^;]*;[^\a]*\a))`)
	return utf8.RuneCountInString(re.ReplaceAllString(content, ""))
}

A length_test.go => length_test.go +60 -0
@@ 0,0 1,60 @@
package ansi

import (
	"fmt"
	"testing"
)

func TestLength(t *testing.T) {
	tests := []struct {
		name           string
		input          string
		expectedLength int
	}{
		{
			name:           "color",
			input:          Blue("4444"),
			expectedLength: 4,
		},
		{
			name:           "formatting",
			input:          Bold("88888888"),
			expectedLength: 8,
		},
		{
			name:           "link",
			input:          LinkString("https://example.com", "333"),
			expectedLength: 3,
		},
		{
			name:           "notification",
			input:          SendNotification("some title", "some body"),
			expectedLength: 0,
		},
		{
			name:           "movement",
			input:          fmt.Sprintf("Up%s3x%s", Up(), UpX(400)),
			expectedLength: 4,
		},
		{
			name:           "cursor-save",
			input:          fmt.Sprintf("Save%sRestore%s:)", SavePos(), RestorePos()),
			expectedLength: 13,
		},
		{
			name:           "clear-screen",
			input:          fmt.Sprintf("clear%s", ClearScreen()),
			expectedLength: 5,
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			if l := GetLengthWithoutCodes(test.input); l != test.expectedLength {
				t.Logf("expected length %d, but got %d", test.expectedLength, l)
				fmt.Printf("%x", GetLengthWithoutCodes(test.input))
				t.Fail()
			}
		})
	}
}