/
info.go
69 lines (56 loc) · 1.16 KB
/
info.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
package file
import (
"errors"
"fmt"
"io"
"log"
"os"
"github.com/edutko/what-is/internal/units"
)
type Info struct {
Path string
Size int64
Description string
Attributes []Attribute
Children []Info
}
type Attribute struct {
Name string
Value string
}
var ErrNotRegularFile = errors.New("only regular files are supported")
var MaxReadSize = 128 * units.Megabyte
func Inspect(f *os.File) (Info, error) {
info := Info{Path: f.Name()}
s, err := f.Stat()
if err != nil {
return info, fmt.Errorf("os.Stat: %w", err)
}
if s.Mode().IsRegular() {
info.Size = s.Size()
}
r := io.LimitReader(f, MaxReadSize)
data, err := io.ReadAll(r)
if err != nil {
return info, fmt.Errorf("f.Read: %w", err)
}
for _, parse := range candidateParsers(info, data) {
var i Info
i, err := parse(info, data)
if err != nil {
log.Println(err)
} else {
return i, nil
}
}
return info, nil
}
func candidateParsers(info Info, data []byte) []Parser {
var ps []Parser
for _, p := range filetypes {
if p.MatchesName(info.Path) || p.MatchesMagic(data) || p.SmellsLike(info.Path, data, info.Size) {
ps = append(ps, p.parser)
}
}
return ps
}