-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
85 lines (75 loc) · 1.67 KB
/
main.go
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
package main // import "4d63.com/tldr"
import (
"flag"
"fmt"
"os"
"regexp"
"strings"
"github.com/fatih/color"
)
var version = "<not set>"
func main() {
flagPrintVersion := flag.Bool("version", false, "")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Tldr provides simplified and community-driven man pages.\n")
fmt.Fprintf(os.Stderr, "Usage: tldr <command>\n")
fmt.Fprintf(os.Stderr, "Example: tldr tar\n")
}
flag.Parse()
if *flagPrintVersion {
fmt.Println("tldr", "v"+version)
return
}
args := flag.Args()
if len(args) == 0 {
flag.Usage()
return
}
if len(args) > 1 {
fmt.Fprintf(os.Stderr, "A single command must be specified.\n")
os.Exit(1)
}
command := strings.ToLower(args[0])
raw, ok := files[command]
if !ok {
raw, ok = commonFiles[command]
if !ok {
fmt.Fprintf(os.Stderr, "Command %s is not known.\n", command)
os.Exit(1)
}
}
text := string(raw)
fmt.Fprint(color.Output, pretty(text))
}
func pretty(s string) string {
sep := "\n"
lines := strings.Split(s, sep)
lastLine := ""
prettyLines := []string{}
for _, l := range lines {
if len(lastLine) > 0 && lastLine[0] == '-' && len(l) == 0 {
continue
}
lastLine = l
if len(l) > 0 {
switch l[0] {
case '#':
l = strings.TrimSpace(l[1:])
case '>':
l = strings.TrimSpace(l[1:])
case '-':
l = "-" + color.YellowString(l[1:])
case '`':
l = strings.Trim(l, "`")
r := regexp.MustCompile(`{{|}}`)
parts := r.Split(l, -1)
for i := 0; i < len(parts); i += 2 {
parts[i] = color.GreenString(parts[i])
}
l = " " + strings.Join(parts, "")
}
}
prettyLines = append(prettyLines, l)
}
return strings.Join(prettyLines, sep)
}