-
Notifications
You must be signed in to change notification settings - Fork 0
/
printer.go
99 lines (83 loc) · 2.07 KB
/
printer.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
package main
import (
"fmt"
"io"
"github.com/gookit/color"
"golang.org/x/xerrors"
)
var (
folderColor = color.New(defaultFolderIcon.Color)
symColor = color.New(color.FgLightCyan)
)
// Printer write FileInfo as tree.
type Printer struct {
opt *ListDisplayOptions
}
// NewPrinter return Printer pointer.
func NewPrinter(opt *ListDisplayOptions) *Printer {
return &Printer{
opt: opt,
}
}
func (p *Printer) writePrefix(w io.Writer, f FileInfo, prefix string) (err error) {
if f.IsLast() {
_, err = w.Write([]byte(prefix + "└── "))
} else {
_, err = w.Write([]byte(prefix + "├── "))
}
if err != nil {
return xerrors.Errorf("failed to write: %w", err)
}
return nil
}
func (p *Printer) Write(w io.Writer, f FileInfo) (err error) {
if pa, ok := f.Parent(); ok {
err = p.writePrefix(w, f, pa.ChildPrefix())
if err != nil {
return xerrors.Errorf("failed to writePrefix: %w", err)
}
}
if !f.IsDir() && !p.opt.NoIcon() {
_, err = w.Write([]byte(NewIconString(f.FileType()) + " "))
if err != nil {
return xerrors.Errorf("failed to write: %w", err)
}
}
var writtenName string
if p.opt.IsFullPath() {
writtenName = f.Path()
} else {
writtenName = f.Name()
}
switch {
case f.IsDir():
if p.opt.NoIcon() {
_, err = w.Write([]byte(folderColor.Sprintf(writtenName)))
} else {
_, err = w.Write([]byte(folderColor.Sprintf("%s %s", defaultFolderIcon.Icon, writtenName)))
}
case f.IsSym():
var symLink string
symLink, err = f.SymLink()
if err != nil {
return xerrors.Errorf("failed to retrieve symlink path: %w", err)
}
_, err = w.Write([]byte(fmt.Sprintf("%s -> %s", symColor.Sprint(writtenName), symLink)))
default:
_, err = w.Write([]byte(writtenName))
}
if err != nil {
return xerrors.Errorf("failed to write: %w", err)
}
if err := f.Error(); err != nil {
_, err = w.Write([]byte(fmt.Sprintf(" [%s]", err.Error())))
if err != nil {
return xerrors.Errorf("failed to write: %w", err)
}
}
_, err = w.Write([]byte("\n"))
if err != nil {
return xerrors.Errorf("failed to write: %w", err)
}
return nil
}