-
Notifications
You must be signed in to change notification settings - Fork 118
/
ccat.go
86 lines (66 loc) · 1.39 KB
/
ccat.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
package main
import (
"bytes"
"io"
"io/ioutil"
"os"
"syscall"
"fmt"
"github.com/mattn/go-isatty"
)
type CCatPrinter interface {
Print(r io.Reader, w io.Writer) error
}
type AutoColorPrinter struct {
ColorPalettes ColorPalettes
}
func (a AutoColorPrinter) Print(r io.Reader, w io.Writer) error {
if isatty.IsTerminal(uintptr(syscall.Stdout)) {
return ColorPrinter{a.ColorPalettes}.Print(r, w)
} else {
return PlainTextPrinter{}.Print(r, w)
}
}
type ColorPrinter struct {
ColorPalettes ColorPalettes
}
func (c ColorPrinter) Print(r io.Reader, w io.Writer) error {
return CPrint(r, w, c.ColorPalettes)
}
type PlainTextPrinter struct {
}
func (p PlainTextPrinter) Print(r io.Reader, w io.Writer) error {
_, err := io.Copy(w, r)
return err
}
type HtmlPrinter struct {
ColorPalettes ColorPalettes
}
func (c HtmlPrinter) Print(r io.Reader, w io.Writer) error {
return HtmlPrint(r, w, c.ColorPalettes)
}
func CCat(fname string, p CCatPrinter, w io.Writer) error {
var r io.Reader
if fname == readFromStdin {
b, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return err
}
r = bytes.NewReader(b)
} else {
file, err := os.Open(fname)
if err != nil {
return err
}
defer file.Close()
fi, err := file.Stat()
if err != nil {
return err
}
if fi.Mode().IsDir() {
return fmt.Errorf("%s is a directory", file.Name())
}
r = file
}
return p.Print(r, w)
}