#!/usr/bin/env bash
set -euo pipefail
cat >> textutil.go <<'GO'
// Truncate shortens s to at most max characters, ending with "..." when it cuts.
func Truncate(s string, max int) string {
r := []rune(s)
if len(r) <= max {
return s
}
if max <= 3 {
return strings.Repeat(".", max)
}
return string(r[:max-3]) + "..."
}
GO
cat >> textutil_test.go <<'GO'
func TestTruncate(t *testing.T) {
if got := Truncate("hello world", 8); got != "hello..." {
t.Errorf("Truncate() = %q", got)
}
if got := Truncate("short", 10); got != "short" {
t.Errorf("Truncate() = %q", got)
}
}
GO