aboutsummaryrefslogtreecommitdiff
path: root/object/tree/insert.go
blob: 5e51906908b2f6d3e37ffb905ba5105ff7073af1 (about) (plain) (blame)
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
package tree

import (
	"errors"
	"fmt"
	"slices"
	"strings"

	"lindenii.org/go/furgit/object/tree/mode"
)

// ErrInvalidTree indicates a malformed tree object or tree entry.
var ErrInvalidTree = errors.New("object/tree: invalid tree")

// Insert adds an entry to the tree while preserving Git tree ordering.
//
// It rejects entries with an invalid name or mode,
// and entries whose name conflicts with one already present.
func (tree *Tree) Insert(entry Entry) error {
	err := validateName(entry.Name)
	if err != nil {
		return err
	}

	if !entry.Mode.IsValid() {
		return fmt.Errorf("%w: entry %q has invalid mode", ErrInvalidTree, entry.Name)
	}

	if _, found := tree.Find(entry.Name); found {
		return fmt.Errorf("%w: entry %q already exists", ErrInvalidTree, entry.Name)
	}

	isTree := entry.Mode == mode.Directory

	insertAt, _ := slices.BinarySearchFunc(tree.entries, entry, func(existing Entry, target Entry) int {
		return nameCompare(existing.Name, existing.Mode == mode.Directory, target.Name, isTree)
	})

	tree.entries = slices.Insert(tree.entries, insertAt, entry)

	return nil
}

// validateName checks that name is a structurally valid tree entry name.
func validateName(name string) error {
	if name == "" {
		return fmt.Errorf("%w: empty entry name", ErrInvalidTree)
	}

	if strings.IndexByte(name, 0) >= 0 {
		return fmt.Errorf("%w: entry name %q contains NUL", ErrInvalidTree, name)
	}

	if strings.IndexByte(name, '/') >= 0 {
		return fmt.Errorf("%w: entry name %q contains '/'", ErrInvalidTree, name)
	}

	return nil
}