mugit/internal/git/tree.go(view raw)
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 |
package git
import (
"errors"
"fmt"
"io"
"mime"
"path"
"path/filepath"
"strings"
"github.com/go-git/go-git/v5/plumbing/object"
)
type NiceTree struct {
IsFile bool
Name string
Commit *Commit
Mode string
Size int64
}
func (g *Repo) makeNiceTree(t *object.Tree, parent string) []NiceTree {
var nts []NiceTree
for _, e := range t.Entries {
mode, _ := e.Mode.ToOSFileMode()
sz, _ := t.Size(e.Name)
// TODO: this should be cached, its pretty expensive
lc, _ := g.lastCommitForFile(path.Join(parent, e.Name))
nts = append(nts, NiceTree{
Name: e.Name,
Mode: mode.String(),
IsFile: e.Mode.IsFile(),
Commit: lc,
Size: sz,
})
}
return nts
}
func (g *Repo) FileTree(path string) ([]NiceTree, error) {
c, err := g.r.CommitObject(g.h)
if err != nil {
return nil, fmt.Errorf("commit object: %w", err)
}
tree, err := c.Tree()
if err != nil {
return nil, fmt.Errorf("file tree: %w", err)
}
var files []NiceTree
if path == "" {
files = g.makeNiceTree(tree, path)
} else {
o, err := tree.FindEntry(path)
if err != nil {
return nil, err
}
if !o.Mode.IsFile() {
subtree, err := tree.Tree(path)
if err != nil {
return nil, err
}
files = g.makeNiceTree(subtree, path)
}
}
return files, nil
}
type FileContent struct {
IsBinary bool
Content []byte
Mime string
Size int64
}
func (fc FileContent) IsImage() bool {
return strings.HasPrefix(fc.Mime, "image/")
}
func (fc *FileContent) String() string {
if fc.IsBinary {
return ""
}
return string(fc.Content)
}
func (g *Repo) FileContent(path string) (*FileContent, error) {
c, err := g.r.CommitObject(g.h)
if err != nil {
return &FileContent{}, fmt.Errorf("commit object: %w", err)
}
tree, err := c.Tree()
if err != nil {
return &FileContent{}, fmt.Errorf("file tree: %w", err)
}
file, err := tree.File(path)
if err != nil {
if errors.Is(err, object.ErrFileNotFound) {
return &FileContent{}, ErrFileNotFound
}
return &FileContent{}, err
}
reader, err := file.Reader()
if err != nil {
return nil, fmt.Errorf("file reader: %w", err)
}
defer reader.Close()
content, err := io.ReadAll(reader)
if err != nil {
return nil, fmt.Errorf("read file: %w", err)
}
isBin, _ := file.IsBinary()
mimeType := mime.TypeByExtension(filepath.Ext(path))
if mimeType == "" {
mimeType = "text/plain"
if isBin {
mimeType = "application/octet-stream"
}
}
return &FileContent{
IsBinary: isBin,
Content: content,
Mime: mimeType,
Size: file.Size,
}, nil
}
|