-
Notifications
You must be signed in to change notification settings - Fork 14
/
docs.go
80 lines (69 loc) · 1.68 KB
/
docs.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
package cmd
import (
"bytes"
"errors"
"fmt"
"io"
"io/fs"
"os"
"rare/cmd/helpers"
"rare/docs"
"rare/pkg/markdowncli"
"strings"
"github.com/urfave/cli"
)
func docsFunction(c *cli.Context) error {
docname := strings.ToLower(c.Args().First())
if docname == "" || docname == "list" {
listDocFiles()
} else if file, err := openDocFileByPartialName(docname); err == nil {
var buf bytes.Buffer
markdowncli.WriteMarkdownToBuf(&buf, file)
if c.Bool("no-pager") || helpers.TryWritePager(&buf) != nil {
io.Copy(os.Stdout, &buf)
}
} else {
return cli.NewExitError(fmt.Sprintf("No such doc '%s'", docname), helpers.ExitCodeInvalidUsage)
}
return nil
}
func listDocFiles() {
fmt.Println("Available Docs:")
entries, _ := docs.DocFS.ReadDir(docs.BasePath)
for _, entry := range entries {
fmt.Printf(" %s\n", strings.TrimSuffix(entry.Name(), ".md"))
}
}
func openDocFileByPartialName(s string) (fs.File, error) {
s = strings.ToLower(s)
// Try exact match
if f, err := docs.DocFS.Open(docs.BasePath + "/" + s + ".md"); err == nil {
return f, nil
}
// Search for prefix of name
entries, _ := docs.DocFS.ReadDir(docs.BasePath)
for _, entry := range entries {
if strings.HasPrefix(entry.Name(), s) {
fullPath := docs.BasePath + "/" + entry.Name()
f, err := docs.DocFS.Open(fullPath)
if err == nil {
return f, nil
}
}
}
return nil, errors.New("no such file")
}
func docsCommand() *cli.Command {
return &cli.Command{
Name: "docs",
Usage: "Access detailed documentation",
ArgsUsage: "[doc]",
Action: docsFunction,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "no-pager,n",
Usage: "Don't use pager to view documentation",
},
},
}
}