generated from Yakiyo/go-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
111 lines (97 loc) · 2.29 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
package main
import (
"errors"
"fmt"
"os"
"strings"
"github.com/alecthomas/chroma/lexers"
"github.com/charmbracelet/log"
"github.com/spf13/pflag"
)
const version string = "0.1.0"
var (
vf = pflag.BoolP("version", "v", false, "Print version for rat")
hf = pflag.BoolP("help", "h", false, "Print help")
ff = pflag.BoolP("force", "f", false, "Pretty print even if output is not a tty")
af = pflag.Bool("list", false, "List all supported languages")
lf = pflag.StringP("language", "l", "", "Select language to use")
sf = pflag.String("style", "dracula", "Choose chroma style to use")
)
func run() error {
if *vf {
fmt.Println("Rat version", version)
return nil
}
if *hf {
pflag.Usage()
return nil
}
if *af {
for _, lang := range lexers.Names(false) {
fmt.Println(lang)
}
}
args := pflag.Args()
if len(args) < 1 {
args = append(args, "-")
}
files := []file{}
// keep reusing this shit
var f file
for _, arg := range args {
if arg == "-" {
str, err := readStdin()
if err != nil {
// log.Error("Unexpected error when reading input from stdin", "err", err)
err = errors.Join(errors.New("unexpected error when reading input from stdin"), err)
return err
}
f = file{
content: strings.Join(str, "\n"),
filename: "-",
}
} else {
bytes, err := os.ReadFile(arg)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("no file exists at path %s", arg)
}
return errors.Join(errors.New("error when trying to read file"), err)
}
f = file{
content: string(bytes),
filename: arg,
}
}
files = append(files, f)
}
_, noc := os.LookupEnv("NO_COLOR")
for _, file := range files {
log.Info("printing file", "filename", file.filename)
if *sf == "none" || noc || (!isAtty() && !*ff) {
fmt.Println(file.content)
continue
}
err := file.format()
if err != nil {
return err
}
}
return nil
}
func main() {
initLogger()
pflag.Usage = func() {
fmt.Fprintln(os.Stderr, "Concatenate FILE(s) to standard output.")
fmt.Fprintln(os.Stderr, "Usage: rat [OPTIONS] [ARGS]")
fmt.Fprintln(os.Stderr, "When no args is provided or `-` is given, stdin is used for input")
fmt.Fprintln(os.Stderr)
pflag.PrintDefaults()
}
pflag.Parse()
err := run()
if err != nil {
log.Error(err)
os.Exit(1)
}
}