1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
| package main
import ( "bufio" "fmt" "io" "os" "strings" "unicode/utf8" )
func main() { info, _ := os.Stdin.Stat()
if info.Mode()&os.ModeCharDevice != 0 { fmt.Println("The command is intended to work with pipes.") fmt.Println("Usage: fortune | gocowsay") return }
var lines []string
reader := bufio.NewReader(os.Stdin)
for { line, _, err := reader.ReadLine() if err != nil && err == io.EOF { break } lines = append(lines, string(line)) }
var cow = ` \ ^__^ \ (oo)\_______ (__)\ )\/\ ||----w | || || `
lines = tabsToSpaces(lines) maxwidth := calculateMaxWidth(lines) messages := normalizeStringsLength(lines, maxwidth) balloon := buildBalloon(messages, maxwidth) fmt.Println(balloon) fmt.Println(cow) fmt.Println() }
func tabsToSpaces(lines []string) []string { var ret []string for _, l := range lines { l = strings.Replace(l, "\t", " ", -1) ret = append(ret, l) } return ret }
func calculateMaxWidth(lines []string) int { w := 0 for _, l := range lines { len := utf8.RuneCountInString(l) if len > w { w = len } }
return w }
func normalizeStringsLength(lines []string, maxwidth int) []string { var ret []string for _, l := range lines { s := l + strings.Repeat(" ", maxwidth-utf8.RuneCountInString(l)) ret = append(ret, s) } return ret }
func buildBalloon(lines []string, maxwidth int) string { var borders []string count := len(lines) var ret []string
borders = []string{"/", "\\", "\\", "/", "|", "<", ">"}
top := " " + strings.Repeat("_", maxwidth+2) bottom := " " + strings.Repeat("-", maxwidth+2)
ret = append(ret, top) if count == 1 { s := fmt.Sprintf("%s %s %s", borders[5], lines[0], borders[6]) ret = append(ret, s) } else { s := fmt.Sprintf(`%s %s %s`, borders[0], lines[0], borders[1]) ret = append(ret, s) i := 1 for ; i < count-1; i++ { s = fmt.Sprintf(`%s %s %s`, borders[4], lines[i], borders[4]) ret = append(ret, s) } s = fmt.Sprintf(`%s %s %s`, borders[2], lines[i], borders[3]) ret = append(ret, s) }
ret = append(ret, bottom) return strings.Join(ret, "\n") }
|