summaryrefslogtreecommitdiff
path: root/signature.go
blob: dfd97189c65a3669d261de56d1b0ab5dd17cbf15 (plain)
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
package git

/*
#include <git2.h>
*/
import "C"
import (
	"runtime"
	"time"
	"unsafe"
)

type Signature struct {
	Name  string
	Email string
	When  time.Time
}

func newSignatureFromC(sig *C.git_signature) *Signature {
	if sig == nil {
		return nil
	}

	// git stores minutes, go wants seconds
	loc := time.FixedZone("", int(sig.when.offset)*60)
	return &Signature{
		C.GoString(sig.name),
		C.GoString(sig.email),
		time.Unix(int64(sig.when.time), 0).In(loc),
	}
}

// Offset returns the time zone offset of v.When in minutes, which is what git wants.
func (v *Signature) Offset() int {
	_, offset := v.When.Zone()
	return offset / 60
}

func (sig *Signature) toC() (*C.git_signature, error) {
	if sig == nil {
		return nil, nil
	}

	var out *C.git_signature

	runtime.LockOSThread()
	defer runtime.UnlockOSThread()

	name := C.CString(sig.Name)
	defer C.free(unsafe.Pointer(name))

	email := C.CString(sig.Email)
	defer C.free(unsafe.Pointer(email))

	ret := C.git_signature_new(&out, name, email, C.git_time_t(sig.When.Unix()), C.int(sig.Offset()))
	if ret < 0 {
		return nil, MakeGitError(ret)
	}

	return out, nil
}

func (repo *Repository) DefaultSignature() (*Signature, error) {
	var out *C.git_signature

	runtime.LockOSThread()
	defer runtime.UnlockOSThread()

	cErr := C.git_signature_default(&out, repo.ptr)
	runtime.KeepAlive(repo)
	if cErr < 0 {
		return nil, MakeGitError(cErr)
	}

	defer C.git_signature_free(out)

	return newSignatureFromC(out), nil
}