-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
262 lines (232 loc) · 7.23 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
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
package main
import (
"fmt"
"io"
"os"
"regexp"
"runtime"
"runtime/debug"
"strings"
"github.com/batmac/ccat/pkg/color"
"github.com/batmac/ccat/pkg/completion"
"github.com/batmac/ccat/pkg/globalctx"
"github.com/batmac/ccat/pkg/highlighter"
"github.com/batmac/ccat/pkg/log"
"github.com/batmac/ccat/pkg/mutators"
"github.com/batmac/ccat/pkg/openers"
"github.com/batmac/ccat/pkg/secretprovider"
"github.com/batmac/ccat/pkg/selfupdate"
"github.com/batmac/ccat/pkg/term"
flag "github.com/spf13/pflag"
)
var (
argTokens = flag.StringP("tokens", "t", "", "comma-separated list of tokens")
argInsensitive = flag.BoolP("ignore-case", "i", false, "tokens given with -t are case-insensitive")
argOnlyMatching = flag.BoolP("only", "o", false, "don't display lines without at least one token")
argRaw = flag.BoolP("raw", "r", false, "don't treat tokens as regexps")
argLineNumber = flag.BoolP("line-number", "n", false, "number the output lines, starting at 1.")
argLockIn = flag.BoolP("flock-in", "L", false, "exclusively flock each file before reading")
argLockOut = flag.BoolP("flock-out", "l", false, "exclusively flock stdout")
argSplitByWords = flag.BoolP("word", "w", false, "read word by word instead of line by line (only works with utf8)")
argBG = flag.BoolP("bg", "b", false, "colorize the background instead of the font")
argHuman = flag.BoolP("humanize", "H", false, "try to do what is needed to help (syntax-highlight, autodetect, etc.)")
argStyle = flag.StringP("style", "S", "", "style to use (only used if -H, --fullhelp for the list)")
argFormatter = flag.StringP("formatter", "F", "", "formatter to use (only used if -H, --fullhelp for the list)")
argLexer = flag.StringP("lexer", "P", "", "lexer to use (only used if -H, --fullhelp for the list)")
argMutators = flag.StringP("mutators", "m", "", "mutators to use (comma-separated), --fullhelp for the list")
argVersion = flag.BoolP("version", "V", false, "print version on stdout")
argLicense = flag.Bool("license", false, "print license on stdout")
argBuildInfo = flag.BoolP("buildinfo", "B", false, "print build info on stdout")
argHelp = flag.BoolP("help", "h", false, "print usage on stderr")
argFullHelp = flag.BoolP("fullhelp", "", false, "print full usage on stdout")
argSelfUpdate = flag.Bool("selfupdate", false, "Update to latest Github release")
argCheckUpdate = flag.Bool("check", false, "Check version with the latest Github release")
argForceUpdate = flag.Bool("forceupdate", false, "Force overwriting to the latest Github release")
argDebug = flag.BoolP("debug", "d", false, "debug what we are doing")
argMemUsage = flag.BoolP("mem-usage", "M", false, "print memory usage on stderr at the end")
argInsecure = flag.BoolP("insecure", "k", false, "get files insecurely (globally)")
argCompletion = flag.StringP("completion", "C", "", "print shell completion script")
argLess = flag.BoolP("ui", "T", false, "display with a minimal ui")
argPprof = flag.Bool("pprof", false, "enable cpu and mem profiling")
argSetKey = new(bool) // set by init()
tmap map[string]color.Color
tokens []string
)
var (
// these are set by the build tool
version = "unknown"
commit = "unknown"
date = "unknown"
builtBy = "unknown"
tags = "unknown"
)
func init() {
if secretprovider.IsKeystoreAvailable {
argSetKey = flag.BoolP("setkey", "", false, "interactively ask and store a secret in the OS keyring")
}
flag.Usage = Usage
flag.Parse()
if !*argDebug {
log.SetDebug(io.Discard)
} else {
log.SetDebug(os.Stderr)
}
}
func main() {
log.Debugln("STARTING ccat")
log.Debugf(buildLine())
if *argPprof {
log.Debugln("pprof enabled")
enablePprof()
defer endPprof()
}
if *argSetKey {
interactivelySetKey()
os.Exit(0) //nolint
}
if *argVersion {
fmt.Println(buildLine())
os.Exit(0)
}
if *argLicense {
fmt.Println(buildLine())
printLicense(os.Stdout)
os.Exit(0)
}
if *argBuildInfo {
b := strings.Builder{}
b.WriteString(buildLine())
bi, ok := debug.ReadBuildInfo()
if !ok {
log.Fatal("failed to read build info")
}
b.WriteString(bi.String())
var s string
if *argHuman {
s = highlighter.Run(b.String(), highlighter.NewOptions(
"",
strings.ToLower(*argStyle),
strings.ToLower(*argFormatter),
"go"))
} else {
s = b.String()
}
fmt.Println(s)
os.Exit(0)
}
if len(*argCompletion) > 0 {
var opts []string
flag.VisitAll(func(f *flag.Flag) {
if len(f.Shorthand) > 0 {
opts = append(opts, "-"+f.Shorthand)
}
opts = append(opts, "--"+f.Name)
})
completion.Print(*argCompletion, opts)
os.Exit(0)
}
if *argHelp {
Usage()
os.Exit(0)
}
if *argFullHelp {
FullUsage()
os.Exit(0)
}
if *argSelfUpdate {
selfupdate.Do(version, tags, selfupdate.ModeUpdate)
os.Exit(0)
}
if *argCheckUpdate {
selfupdate.Do(version, tags, selfupdate.ModeCheckOnly)
os.Exit(0)
}
if *argForceUpdate {
selfupdate.Do(version, tags, selfupdate.ModeForce)
os.Exit(0)
}
if term.IsStdoutTerminal() {
*argHuman = true
}
if len(*argTokens) > 0 {
log.Debugln("initializing tokens...")
if *argRaw {
*argTokens = regexp.QuoteMeta(*argTokens)
}
tokens = strings.Split(*argTokens, ",")
log.Debugf("tokens: %v\n", tokens)
log.Debugln("initializing colors...")
tmap = make(map[string]color.Color)
var c color.Color
if *argBG {
c = new(color.ANSIbg)
} else {
c = new(color.ANSI)
}
for _, s := range tokens {
c = c.Next()
tmap[s] = c
}
}
// fmt.Printf("%v\n", tmap)
log.Debugln("initializing file list...")
fileList := flag.Args()
if len(fileList) == 0 {
fileList = []string{"-"}
}
log.Debugf("files: %v\n", fileList)
if err := setupStdout(*argLockOut); err != nil {
log.Fatal(err)
}
log.Debugln("processing...")
process := processFile
if !term.IsStdoutTerminal() && (flag.NFlag() == 0 || (flag.NFlag() == 1 && *argDebug)) {
log.Debugln("no option given, trying to be as fast as possible")
process = processFileAsIs
}
if *argLess {
if *argDebug {
log.Fatal("aborting, because the ui option is not compatible with the debug option")
}
process = uiWrapProcessFile(process)
}
for _, path := range fileList {
globalctx.Reset()
globalctx.Set("fileList", fileList)
globalctx.Set("insecure", *argInsecure)
process(os.Stdout, path)
}
if *argMemUsage {
PrintMemUsage()
}
if globalctx.IsErrored() {
os.Exit(1)
}
}
func buildLine() string {
return fmt.Sprintf("version %s [%s], commit %s, built at %s by %s (%s %s/%s)",
version, tags, commit, date, builtBy, runtime.Version(), runtime.GOOS, runtime.GOARCH)
}
func Usage() {
usage(os.Stderr, false)
}
func FullUsage() {
usage(os.Stdout, true)
}
func usage(w io.Writer, full bool) {
flag.CommandLine.SortFlags = false
flag.CommandLine.SetOutput(w)
fmt.Fprintln(w, buildLine())
fmt.Fprintln(w, "usage: ccat [options] [file ...]")
flag.PrintDefaults()
fmt.Fprintln(w, "")
if !full {
return
}
fmt.Fprintln(w, "---")
fmt.Fprint(w, "ccat <files>...\n")
fmt.Fprint(w, " - highlighter (used with -H):\n")
fmt.Fprint(w, highlighter.Help())
fmt.Fprintf(w, " - openers:\n %v\n", strings.Join(openers.ListOpenersWithDescription(), "\n "))
fmt.Fprintf(w, " - mutators:\n%v\n", mutators.AvailableMutatorsHelp())
}