Skip to content
This repository was archived by the owner on Sep 11, 2020. It is now read-only.

Commit 4cbf210

Browse files
authored
Merge pull request #534 from josharian/firstparent
plumbing: object, commit.Parent() method
2 parents 65b4be3 + e09fa24 commit 4cbf210

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

plumbing/object/commit.go

+12
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package object
33
import (
44
"bufio"
55
"bytes"
6+
"errors"
67
"fmt"
78
"io"
89
"strings"
@@ -98,6 +99,17 @@ func (c *Commit) NumParents() int {
9899
return len(c.ParentHashes)
99100
}
100101

102+
var ErrParentNotFound = errors.New("commit parent not found")
103+
104+
// Parent returns the ith parent of a commit.
105+
func (c *Commit) Parent(i int) (*Commit, error) {
106+
if len(c.ParentHashes) == 0 || i > len(c.ParentHashes)-1 {
107+
return nil, ErrParentNotFound
108+
}
109+
110+
return GetCommit(c.s, c.ParentHashes[i])
111+
}
112+
101113
// File returns the file with the specified "path" in the commit and a
102114
// nil error if the file exists. If the file does not exist, it returns
103115
// a nil file and the ErrFileNotFound error.

plumbing/object/commit_test.go

+12
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,18 @@ func (s *SuiteCommit) TestParents(c *C) {
6767
i.Close()
6868
}
6969

70+
func (s *SuiteCommit) TestParent(c *C) {
71+
commit, err := s.Commit.Parent(1)
72+
c.Assert(err, IsNil)
73+
c.Assert(commit.Hash.String(), Equals, "a5b8b09e2f8fcb0bb99d3ccb0958157b40890d69")
74+
}
75+
76+
func (s *SuiteCommit) TestParentNotFound(c *C) {
77+
commit, err := s.Commit.Parent(42)
78+
c.Assert(err, Equals, ErrParentNotFound)
79+
c.Assert(commit, IsNil)
80+
}
81+
7082
func (s *SuiteCommit) TestPatch(c *C) {
7183
from := s.commit(c, plumbing.NewHash("918c48b83bd081e863dbe1b80f8998f058cd8294"))
7284
to := s.commit(c, plumbing.NewHash("6ecf0ef2c2dffb796033e5a02219af86ec6584e5"))

0 commit comments

Comments
 (0)