Add support for parsing git trailers

Adds a wrapper for git_message_trailers which returns a slice of trailer
structs.
This commit is contained in:
Jesse Hathaway 2020-06-01 21:41:53 +00:00
parent 31f877e249
commit 482da8fcb0
2 changed files with 82 additions and 0 deletions

40
message.go Normal file
View File

@ -0,0 +1,40 @@
package git
/*
#include <git2.h>
*/
import "C"
import (
"runtime"
"unsafe"
)
type Trailer struct {
key string
value string
}
func MessageTrailers(message string) ([]Trailer, error) {
var trailersC C.git_message_trailer_array
messageC := C.CString(message)
defer C.free(unsafe.Pointer(messageC))
runtime.LockOSThread()
defer runtime.UnlockOSThread()
ecode := C.git_message_trailers(&trailersC, messageC)
if ecode < 0 {
return nil, MakeGitError(ecode)
}
defer C.git_message_trailer_array_free(&trailersC)
trailers := make([]Trailer, trailersC.count)
var trailer *C.git_message_trailer
for i, p := 0, uintptr(unsafe.Pointer(trailersC.trailers)); i < int(trailersC.count); p += unsafe.Sizeof(C.git_message_trailer{}) {
trailer = (*C.git_message_trailer)(unsafe.Pointer(p))
trailers[i] = Trailer{key: C.GoString(trailer.key), value: C.GoString(trailer.value)}
i++
}
return trailers, nil
}

42
message_test.go Normal file
View File

@ -0,0 +1,42 @@
package git
import (
"fmt"
"reflect"
"testing"
)
func TestTrailers(t *testing.T) {
t.Parallel()
tests := []struct {
input string
expected []Trailer
}{
{
"commit with zero trailers\n",
[]Trailer{},
},
{
"commit with one trailer\n\nCo-authored-by: Alice <alice@example.com>\n",
[]Trailer{
Trailer{key: "Co-authored-by", value: "Alice <alice@example.com>"},
},
},
{
"commit with two trailers\n\nCo-authored-by: Alice <alice@example.com>\nSigned-off-by: Bob <bob@example.com>\n",
[]Trailer{
Trailer{key: "Co-authored-by", value: "Alice <alice@example.com>"},
Trailer{key: "Signed-off-by", value: "Bob <bob@example.com>"}},
},
}
for _, test := range tests {
fmt.Printf("%s", test.input)
actual, err := MessageTrailers(test.input)
if err != nil {
t.Errorf("Trailers returned an unexpected error: %v", err)
}
if !reflect.DeepEqual(test.expected, actual) {
t.Errorf("expecting %#v\ngot %#v", test.expected, actual)
}
}
}