aboutsummaryrefslogtreecommitdiff
path: root/internal/testgit/commit.go
blob: a608d2fa34fc753eb07a6b35e6cd362c166461d7 (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package testgit

import (
	"fmt"
	"strings"
	"testing"

	"lindenii.org/go/furgit/object/id"
)

// CommitTreeIdentity configures an author or committer identity
// for [Repo.CommitTree].
type CommitTreeIdentity struct {
	Name  string
	Email string
}

// CommitTreeOptions configures [Repo.CommitTree].
type CommitTreeOptions struct {
	Message       string
	Author        CommitTreeIdentity
	Committer     CommitTreeIdentity
	AuthorDate    string
	CommitterDate string
}

// CommitTree creates a commit object from a tree and optional parents,
// and returns its object ID.
func (repo *Repo) CommitTree(
	tb testing.TB,
	tree id.ObjectID,
	opts CommitTreeOptions,
	parents ...id.ObjectID,
) (id.ObjectID, error) {
	tb.Helper()

	args := make([]string, 0, 1+2*len(parents)+4)
	args = append(args, "commit-tree")

	for _, parent := range parents {
		args = append(args, "-p", parent.String())
	}

	args = append(args, "-m", opts.Message, "--end-of-options", tree.String())

	cmd := repo.Command(tb, "git", args...)
	if opts.Author.Name != "" {
		cmd.Env = setEnv(cmd.Env, "GIT_AUTHOR_NAME", opts.Author.Name)
	}

	if opts.Author.Email != "" {
		cmd.Env = setEnv(cmd.Env, "GIT_AUTHOR_EMAIL", opts.Author.Email)
	}

	if opts.AuthorDate != "" {
		cmd.Env = setEnv(cmd.Env, "GIT_AUTHOR_DATE", opts.AuthorDate)
	}

	if opts.Committer.Name != "" {
		cmd.Env = setEnv(cmd.Env, "GIT_COMMITTER_NAME", opts.Committer.Name)
	}

	if opts.Committer.Email != "" {
		cmd.Env = setEnv(cmd.Env, "GIT_COMMITTER_EMAIL", opts.Committer.Email)
	}

	if opts.CommitterDate != "" {
		cmd.Env = setEnv(cmd.Env, "GIT_COMMITTER_DATE", opts.CommitterDate)
	}

	stdout, err := cmd.Output()
	if err != nil {
		return id.ObjectID{}, fmt.Errorf("commit-tree: %w", err)
	}

	commitID, err := repo.objectFormat.FromString(strings.TrimSuffix(string(stdout), "\n"))
	if err != nil {
		return id.ObjectID{}, fmt.Errorf("parse git commit-tree output %q: %w", string(stdout), err)
	}

	return commitID, nil
}