diff --git a/tools/str_tools.go b/tools/str_tools.go index d151b0da..b400703c 100644 --- a/tools/str_tools.go +++ b/tools/str_tools.go @@ -100,3 +100,15 @@ func Longest(strs []string) string { return longest } + +// Indent returns a string which prepends "\t" TAB characters to the beginning +// of each line in the given string "str". +func Indent(str string) string { + indented := strings.Replace(str, "\n", "\n\t", -1) + if len(indented) > 0 { + indented = "\t" + indented + } + + return indented +} + diff --git a/tools/str_tools_test.go b/tools/str_tools_test.go index 6f803db9..ea38e382 100644 --- a/tools/str_tools_test.go +++ b/tools/str_tools_test.go @@ -112,3 +112,21 @@ func TestLjustLeftJustifiesString(t *testing.T) { assert.Equal(t, expected, Ljust(unjust)) } + +func TestIndentIndentsStrings(t *testing.T) { + assert.Equal(t, "\tfoo\n\tbar", Indent("foo\nbar")) +} + +func TestIndentIndentsSingleLineStrings(t *testing.T) { + assert.Equal(t, "\tfoo", Indent("foo")) +} + +func TestIndentReturnsEmptyStrings(t *testing.T) { + assert.Equal(t, "", Indent("")) +} + +func TestUndentRemovesLeadingWhitespace(t *testing.T) { + assert.Equal(t, "foo", Undent("\t\t\tfoo")) + assert.Equal(t, "foo", Undent("foo")) + assert.Equal(t, "foo", Undent(" foo")) +} diff --git a/tools/text.go b/tools/text.go new file mode 100644 index 00000000..f7eca129 --- /dev/null +++ b/tools/text.go @@ -0,0 +1 @@ +package tools diff --git a/tools/text_test.go b/tools/text_test.go new file mode 100644 index 00000000..379b5905 --- /dev/null +++ b/tools/text_test.go @@ -0,0 +1 @@ +package tools_test