forked from twpayne/chezmoi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocscmd.go
More file actions
100 lines (89 loc) · 2.04 KB
/
docscmd.go
File metadata and controls
100 lines (89 loc) · 2.04 KB
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
package cmd
import (
"fmt"
"io"
"os"
"regexp"
"strings"
"github.com/charmbracelet/glamour"
"github.com/spf13/cobra"
"golang.org/x/term"
"github.com/twpayne/chezmoi/v2/docs"
)
func (c *Config) newDocsCmd() *cobra.Command {
docsCmd := &cobra.Command{
Use: "docs [regexp]",
Short: "Print documentation",
Long: mustLongHelp("docs"),
Example: example("docs"),
Args: cobra.MaximumNArgs(1),
RunE: c.runDocsCmd,
Annotations: map[string]string{
doesNotRequireValidConfig: "true",
},
}
return docsCmd
}
func (c *Config) runDocsCmd(cmd *cobra.Command, args []string) error {
filename := "REFERENCE.md"
if len(args) > 0 {
pattern := args[0]
re, err := regexp.Compile(strings.ToLower(pattern))
if err != nil {
return err
}
dirEntries, err := docs.FS.ReadDir(".")
if err != nil {
return err
}
var filenames []string
for _, dirEntry := range dirEntries {
fileInfo, err := dirEntry.Info()
if err != nil {
return err
}
if fileInfo.Mode()&^os.ModePerm != 0 {
continue
}
if filename := dirEntry.Name(); re.FindStringIndex(strings.ToLower(filename)) != nil {
filenames = append(filenames, filename)
}
}
switch {
case len(filenames) == 0:
return fmt.Errorf("%s: no matching files", pattern)
case len(filenames) == 1:
filename = filenames[0]
default:
return fmt.Errorf("%s: ambiguous pattern, matches %s", pattern, strings.Join(filenames, ", "))
}
}
file, err := docs.FS.Open(filename)
if err != nil {
return err
}
defer file.Close()
documentData, err := io.ReadAll(file)
if err != nil {
return err
}
width := 80
if stdout, ok := c.stdout.(*os.File); ok && term.IsTerminal(int(stdout.Fd())) {
width, _, err = term.GetSize(int(stdout.Fd()))
if err != nil {
return err
}
}
tr, err := glamour.NewTermRenderer(
glamour.WithStyles(glamour.ASCIIStyleConfig),
glamour.WithWordWrap(width),
)
if err != nil {
return err
}
renderedData, err := tr.RenderBytes(documentData)
if err != nil {
return err
}
return c.writeOutput(renderedData)
}