| 1 |
package fsnoder |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"fmt" |
| 6 |
"hash/fnv" |
| 7 |
|
| 8 |
"github.com/go-git/go-git/v5/utils/merkletrie/noder" |
| 9 |
) |
| 10 |
|
| 11 |
// file values represent file-like noders in a merkle trie. |
| 12 |
type file struct { |
| 13 |
name string // relative |
| 14 |
contents string |
| 15 |
hash []byte // memoized |
| 16 |
} |
| 17 |
|
| 18 |
// newFile returns a noder representing a file with the given contents. |
| 19 |
func newFile(name, contents string) (*file, error) { |
| 20 |
if name == "" { |
| 21 |
return nil, fmt.Errorf("files cannot have empty names") |
| 22 |
} |
| 23 |
|
| 24 |
return &file{ |
| 25 |
name: name, |
| 26 |
contents: contents, |
| 27 |
}, nil |
| 28 |
} |
| 29 |
|
| 30 |
// The hash of a file is just its contents. |
| 31 |
// Empty files will have the fnv64 basis offset as its hash. |
| 32 |
func (f *file) Hash() []byte { |
| 33 |
if f.hash == nil { |
| 34 |
h := fnv.New64a() |
| 35 |
h.Write([]byte(f.contents)) // it never returns an error. |
| 36 |
f.hash = h.Sum(nil) |
| 37 |
} |
| 38 |
|
| 39 |
return f.hash |
| 40 |
} |
| 41 |
|
| 42 |
func (f *file) Name() string { |
| 43 |
return f.name |
| 44 |
} |
| 45 |
|
| 46 |
func (f *file) IsDir() bool { |
| 47 |
return false |
| 48 |
} |
| 49 |
|
| 50 |
func (f *file) Children() ([]noder.Noder, error) { |
| 51 |
return noder.NoChildren, nil |
| 52 |
} |
| 53 |
|
| 54 |
func (f *file) NumChildren() (int, error) { |
| 55 |
return 0, nil |
| 56 |
} |
| 57 |
|
| 58 |
func (f *file) Skip() bool { |
| 59 |
return false |
| 60 |
} |
| 61 |
|
| 62 |
const ( |
| 63 |
fileStartMark = '<' |
| 64 |
fileEndMark = '>' |
| 65 |
) |
| 66 |
|
| 67 |
// String returns a string formatted as: name<contents>. |
| 68 |
func (f *file) String() string { |
| 69 |
var buf bytes.Buffer |
| 70 |
buf.WriteString(f.name) |
| 71 |
buf.WriteRune(fileStartMark) |
| 72 |
buf.WriteString(f.contents) |
| 73 |
buf.WriteRune(fileEndMark) |
| 74 |
|
| 75 |
return buf.String() |
| 76 |
} |