// formatDescr formats a given string (typically a snap description) // in a user friendly way. // // The rules are (intentionally) very simple: // - word wrap at "max" chars // - keep \n intact and break here // - ignore \r func formatDescr(descr string, max int) string { out := bytes.NewBuffer(nil) for _, line := range strings.Split(descr, "\n") { if len(line) > max { for _, chunk := range strutil.WordWrap(line, max) { fmt.Fprintf(out, " %s\n", chunk) } } else { fmt.Fprintf(out, " %s\n", line) } } return strings.TrimSuffix(out.String(), "\n") }
func (ts *strutilSuite) TestWordWrap(c *check.C) { for _, t := range []struct { in string out []string n int }{ // pathological {"12345", []string{"12345"}, 3}, {"123 456789", []string{"123", "456789"}, 3}, // valid {"abc def ghi", []string{"abc", "def", "ghi"}, 3}, {"a b c d e f", []string{"a b", "c d", "e f"}, 3}, {"ab cd ef", []string{"ab cd", "ef"}, 5}, // intentional (but slightly strange) {"ab cd", []string{"ab", "cd"}, 2}, } { c.Check(strutil.WordWrap(t.in, t.n), check.DeepEquals, t.out) } }