From e706b12fcfda85d48f52f7b5f25ae42e548a4895 Mon Sep 17 00:00:00 2001 From: floaust Date: Mon, 5 Sep 2022 02:10:18 +0200 Subject: [PATCH 1/2] feat(putils): add `CenterText` in putils --- internal/center_text.go | 4 ++++ putils/center_text.go | 8 ++++++++ putils/center_text_test.go | 11 +++++++++++ 3 files changed, 23 insertions(+) create mode 100644 putils/center_text.go create mode 100644 putils/center_text_test.go diff --git a/internal/center_text.go b/internal/center_text.go index 79ebb9401..658224a06 100644 --- a/internal/center_text.go +++ b/internal/center_text.go @@ -7,8 +7,12 @@ import ( ) // CenterText returns a centered string with a padding left and right +// If width is 0, it will be calculated automatically func CenterText(text string, width int) string { var lines []string + if width == 0 { + width = GetStringMaxWidth(text) + } linesTmp := strings.Split(text, "\n") for _, line := range linesTmp { if len(color.ClearCode(line)) > width { diff --git a/putils/center_text.go b/putils/center_text.go new file mode 100644 index 000000000..1d383944c --- /dev/null +++ b/putils/center_text.go @@ -0,0 +1,8 @@ +package putils + +import "github.com/pterm/pterm/internal" + +// CenterText returns a centered string with each line centered in respect to the longest line. +func CenterText(text string) string { + return internal.CenterText(text, 0) +} diff --git a/putils/center_text_test.go b/putils/center_text_test.go new file mode 100644 index 000000000..e8f373b37 --- /dev/null +++ b/putils/center_text_test.go @@ -0,0 +1,11 @@ +package putils + +import ( + "testing" + + "github.com/MarvinJWendt/testza" +) + +func TestCenterText(t *testing.T) { + testza.AssertEqual(t, "Hello Wolrd\n !!! ", CenterText("Hello Wolrd\n!!!")) +} From 5bad05a0029276b6e4c11a30cc3f71a2021aea84 Mon Sep 17 00:00:00 2001 From: floaust Date: Mon, 5 Sep 2022 02:16:34 +0200 Subject: [PATCH 2/2] docs(putils): add `CenterText` in docs --- putils/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/putils/README.md b/putils/README.md index be9188c04..d0f5f2940 100644 --- a/putils/README.md +++ b/putils/README.md @@ -14,6 +14,7 @@ Feel free to contribute your utility functions via pull request! func BulletListFromString(s string, padding string) pterm.BulletListPrinter func BulletListFromStrings(s []string, padding string) pterm.BulletListPrinter func BulletListItemFromString(text string, padding string) pterm.BulletListItem +func CenterText(text string) string func DefaultTableFromStructSlice(structSlice interface{}) *pterm.TablePrinter func DownloadFileWithDefaultProgressbar(title, outputPath, url string, mode os.FileMode) error func DownloadFileWithProgressbar(progressbar *pterm.ProgressbarPrinter, outputPath, url string, mode os.FileMode) error