- Notifications
You must be signed in to change notification settings - Fork 324
/
Copy pathgit.go
386 lines (331 loc) · 11.3 KB
/
git.go
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
package git
/*
#include <git2.h>
#include <git2/sys/openssl.h>
*/
import"C"
import (
"bytes"
"encoding/hex"
"errors"
"runtime"
"strings"
"unsafe"
)
//go:generate stringer -type ErrorClass -trimprefix ErrorClass -tags static
typeErrorClassint
const (
ErrorClassNoneErrorClass=C.GIT_ERROR_NONE
ErrorClassNoMemoryErrorClass=C.GIT_ERROR_NOMEMORY
ErrorClassOSErrorClass=C.GIT_ERROR_OS
ErrorClassInvalidErrorClass=C.GIT_ERROR_INVALID
ErrorClassReferenceErrorClass=C.GIT_ERROR_REFERENCE
ErrorClassZlibErrorClass=C.GIT_ERROR_ZLIB
ErrorClassRepositoryErrorClass=C.GIT_ERROR_REPOSITORY
ErrorClassConfigErrorClass=C.GIT_ERROR_CONFIG
ErrorClassRegexErrorClass=C.GIT_ERROR_REGEX
ErrorClassOdbErrorClass=C.GIT_ERROR_ODB
ErrorClassIndexErrorClass=C.GIT_ERROR_INDEX
ErrorClassObjectErrorClass=C.GIT_ERROR_OBJECT
ErrorClassNetErrorClass=C.GIT_ERROR_NET
ErrorClassTagErrorClass=C.GIT_ERROR_TAG
ErrorClassTreeErrorClass=C.GIT_ERROR_TREE
ErrorClassIndexerErrorClass=C.GIT_ERROR_INDEXER
ErrorClassSSLErrorClass=C.GIT_ERROR_SSL
ErrorClassSubmoduleErrorClass=C.GIT_ERROR_SUBMODULE
ErrorClassThreadErrorClass=C.GIT_ERROR_THREAD
ErrorClassStashErrorClass=C.GIT_ERROR_STASH
ErrorClassCheckoutErrorClass=C.GIT_ERROR_CHECKOUT
ErrorClassFetchHeadErrorClass=C.GIT_ERROR_FETCHHEAD
ErrorClassMergeErrorClass=C.GIT_ERROR_MERGE
ErrorClassSSHErrorClass=C.GIT_ERROR_SSH
ErrorClassFilterErrorClass=C.GIT_ERROR_FILTER
ErrorClassRevertErrorClass=C.GIT_ERROR_REVERT
ErrorClassCallbackErrorClass=C.GIT_ERROR_CALLBACK
ErrorClassRebaseErrorClass=C.GIT_ERROR_REBASE
ErrorClassPatchErrorClass=C.GIT_ERROR_PATCH
)
//go:generate stringer -type ErrorCode -trimprefix ErrorCode -tags static
typeErrorCodeint
const (
// ErrorCodeOK indicates that the operation completed successfully.
ErrorCodeOKErrorCode=C.GIT_OK
// ErrorCodeGeneric represents a generic error.
ErrorCodeGenericErrorCode=C.GIT_ERROR
// ErrorCodeNotFound represents that the requested object could not be found
ErrorCodeNotFoundErrorCode=C.GIT_ENOTFOUND
// ErrorCodeExists represents that the object exists preventing operation.
ErrorCodeExistsErrorCode=C.GIT_EEXISTS
// ErrorCodeAmbiguous represents that more than one object matches.
ErrorCodeAmbiguousErrorCode=C.GIT_EAMBIGUOUS
// ErrorCodeBuffs represents that the output buffer is too short to hold data.
ErrorCodeBuffsErrorCode=C.GIT_EBUFS
// ErrorCodeUser is a special error that is never generated by libgit2
// code. You can return it from a callback (e.g to stop an iteration)
// to know that it was generated by the callback and not by libgit2.
ErrorCodeUserErrorCode=C.GIT_EUSER
// ErrorCodeBareRepo represents that the operation not allowed on bare repository
ErrorCodeBareRepoErrorCode=C.GIT_EBAREREPO
// ErrorCodeUnbornBranch represents that HEAD refers to branch with no commits.
ErrorCodeUnbornBranchErrorCode=C.GIT_EUNBORNBRANCH
// ErrorCodeUnmerged represents that a merge in progress prevented operation.
ErrorCodeUnmergedErrorCode=C.GIT_EUNMERGED
// ErrorCodeNonFastForward represents that the reference was not fast-forwardable.
ErrorCodeNonFastForwardErrorCode=C.GIT_ENONFASTFORWARD
// ErrorCodeInvalidSpec represents that the name/ref spec was not in a valid format.
ErrorCodeInvalidSpecErrorCode=C.GIT_EINVALIDSPEC
// ErrorCodeConflict represents that checkout conflicts prevented operation.
ErrorCodeConflictErrorCode=C.GIT_ECONFLICT
// ErrorCodeLocked represents that lock file prevented operation.
ErrorCodeLockedErrorCode=C.GIT_ELOCKED
// ErrorCodeModified represents that the reference value does not match expected.
ErrorCodeModifiedErrorCode=C.GIT_EMODIFIED
// ErrorCodeAuth represents that the authentication failed.
ErrorCodeAuthErrorCode=C.GIT_EAUTH
// ErrorCodeCertificate represents that the server certificate is invalid.
ErrorCodeCertificateErrorCode=C.GIT_ECERTIFICATE
// ErrorCodeApplied represents that the patch/merge has already been applied.
ErrorCodeAppliedErrorCode=C.GIT_EAPPLIED
// ErrorCodePeel represents that the requested peel operation is not possible.
ErrorCodePeelErrorCode=C.GIT_EPEEL
// ErrorCodeEOF represents an unexpected EOF.
ErrorCodeEOFErrorCode=C.GIT_EEOF
// ErrorCodeInvalid represents an invalid operation or input.
ErrorCodeInvalidErrorCode=C.GIT_EINVALID
// ErrorCodeUIncommitted represents that uncommitted changes in index prevented operation.
ErrorCodeUncommittedErrorCode=C.GIT_EUNCOMMITTED
// ErrorCodeDirectory represents that the operation is not valid for a directory.
ErrorCodeDirectoryErrorCode=C.GIT_EDIRECTORY
// ErrorCodeMergeConflict represents that a merge conflict exists and cannot continue.
ErrorCodeMergeConflictErrorCode=C.GIT_EMERGECONFLICT
// ErrorCodePassthrough represents that a user-configured callback refused to act.
ErrorCodePassthroughErrorCode=C.GIT_PASSTHROUGH
// ErrorCodeIterOver signals end of iteration with iterator.
ErrorCodeIterOverErrorCode=C.GIT_ITEROVER
// ErrorCodeRetry is an internal-only error code.
ErrorCodeRetryErrorCode=C.GIT_RETRY
// ErrorCodeMismatch represents a hashsum mismatch in object.
ErrorCodeMismatchErrorCode=C.GIT_EMISMATCH
// ErrorCodeIndexDirty represents that unsaved changes in the index would be overwritten.
ErrorCodeIndexDirtyErrorCode=C.GIT_EINDEXDIRTY
// ErrorCodeApplyFail represents that a patch application failed.
ErrorCodeApplyFailErrorCode=C.GIT_EAPPLYFAIL
)
var (
ErrInvalid=errors.New("Invalid state for operation")
)
// doNotCompare is an idiomatic way of making structs non-comparable to avoid
// future field additions to make them non-comparable.
typedoNotCompare [0]func()
varpointerHandles*HandleList
varremotePointers*remotePointerList
funcinit() {
initLibGit2()
}
funcinitLibGit2() {
pointerHandles=NewHandleList()
remotePointers=newRemotePointerList()
C.git_libgit2_init()
features:=Features()
// Due to the multithreaded nature of Go and its interaction with
// calling C functions, we cannot work with a library that was not built
// with multi-threading support. The most likely outcome is a segfault
// or panic at an incomprehensible time, so let's make it easy by
// panicking right here.
iffeatures&FeatureThreads==0 {
panic("libgit2 was not built with threading support")
}
iffeatures&FeatureHTTPS==0 {
iferr:=registerManagedHTTP(); err!=nil {
panic(err)
}
} else {
// This is not something we should be doing, as we may be stomping all over
// someone else's setup. The user should do this themselves or use some
// binding/wrapper which does it in such a way that they can be sure
// they're the only ones setting it up.
C.git_openssl_set_locking()
}
iffeatures&FeatureSSH==0 {
iferr:=registerManagedSSH(); err!=nil {
panic(err)
}
}
}
// Shutdown frees all the resources acquired by libgit2. Make sure no
// references to any git2go objects are live before calling this.
// After this is called, invoking any function from this library will result in
// undefined behavior, so make sure this is called carefully.
funcShutdown() {
iferr:=unregisterManagedTransports(); err!=nil {
panic(err)
}
pointerHandles.Clear()
remotePointers.clear()
C.git_libgit2_shutdown()
}
// ReInit reinitializes the global state, this is useful if the effective user
// id has changed and you want to update the stored search paths for gitconfig
// files. This function frees any references to objects, so it should be called
// before any other functions are called.
funcReInit() {
Shutdown()
initLibGit2()
}
// Oid represents the id for a Git object.
typeOid [20]byte
funcnewOidFromC(coid*C.git_oid) *Oid {
ifcoid==nil {
returnnil
}
oid:=new(Oid)
copy(oid[0:20], C.GoBytes(unsafe.Pointer(coid), 20))
returnoid
}
funcNewOidFromBytes(b []byte) *Oid {
oid:=new(Oid)
copy(oid[0:20], b[0:20])
returnoid
}
func (oid*Oid) toC() *C.git_oid {
return (*C.git_oid)(unsafe.Pointer(oid))
}
funcNewOid(sstring) (*Oid, error) {
iflen(s) >C.GIT_OID_HEXSZ {
returnnil, errors.New("string is too long for oid")
}
o:=new(Oid)
slice, err:=hex.DecodeString(s)
iferr!=nil {
returnnil, err
}
iflen(slice) !=20 {
returnnil, &GitError{"invalid oid", ErrorClassNone, ErrorCodeGeneric}
}
copy(o[:], slice[:20])
returno, nil
}
func (oid*Oid) String() string {
returnhex.EncodeToString(oid[:])
}
func (oid*Oid) Cmp(oid2*Oid) int {
returnbytes.Compare(oid[:], oid2[:])
}
func (oid*Oid) Copy() *Oid {
ret:=*oid
return&ret
}
func (oid*Oid) Equal(oid2*Oid) bool {
return*oid==*oid2
}
func (oid*Oid) IsZero() bool {
return*oid==Oid{}
}
func (oid*Oid) NCmp(oid2*Oid, nuint) int {
returnbytes.Compare(oid[:n], oid2[:n])
}
funcShortenOids(ids []*Oid, minlenint) (int, error) {
shorten:=C.git_oid_shorten_new(C.size_t(minlen))
ifshorten==nil {
panic("Out of memory")
}
deferC.git_oid_shorten_free(shorten)
varret C.int
runtime.LockOSThread()
deferruntime.UnlockOSThread()
for_, id:=rangeids {
buf:=make([]byte, 41)
C.git_oid_fmt((*C.char)(unsafe.Pointer(&buf[0])), id.toC())
buf[40] =0
ret=C.git_oid_shorten_add(shorten, (*C.char)(unsafe.Pointer(&buf[0])))
ifret<0 {
returnint(ret), MakeGitError(ret)
}
}
runtime.KeepAlive(ids)
returnint(ret), nil
}
typeGitErrorstruct {
Messagestring
ClassErrorClass
CodeErrorCode
}
func (eGitError) Error() string {
returne.Message
}
funcIsErrorClass(errerror, cErrorClass) bool {
iferr==nil {
returnfalse
}
ifgitError, ok:=err.(*GitError); ok {
returngitError.Class==c
}
returnfalse
}
funcIsErrorCode(errerror, cErrorCode) bool {
iferr==nil {
returnfalse
}
ifgitError, ok:=err.(*GitError); ok {
returngitError.Code==c
}
returnfalse
}
funcMakeGitError(c C.int) error {
varerrMessagestring
varerrClassErrorClass
errorCode:=ErrorCode(c)
iferrorCode!=ErrorCodeIterOver {
err:=C.git_error_last()
iferr!=nil {
errMessage=C.GoString(err.message)
errClass=ErrorClass(err.klass)
} else {
errClass=ErrorClassInvalid
}
}
iferrMessage=="" {
errMessage=errorCode.String()
}
return&GitError{errMessage, errClass, errorCode}
}
funcMakeGitError2(errint) error {
returnMakeGitError(C.int(err))
}
funccbool(bbool) C.int {
ifb {
returnC.int(1)
}
returnC.int(0)
}
funcucbool(bbool) C.uint {
ifb {
returnC.uint(1)
}
returnC.uint(0)
}
funcsetCallbackError(errorMessage**C.char, errerror) C.int {
iferr!=nil {
*errorMessage=C.CString(err.Error())
ifgitError, ok:=err.(*GitError); ok {
returnC.int(gitError.Code)
}
returnC.int(ErrorCodeUser)
}
returnC.int(ErrorCodeOK)
}
funcDiscover(startstring, across_fsbool, ceiling_dirs []string) (string, error) {
ceildirs:=C.CString(strings.Join(ceiling_dirs, string(C.GIT_PATH_LIST_SEPARATOR)))
deferC.free(unsafe.Pointer(ceildirs))
cstart:=C.CString(start)
deferC.free(unsafe.Pointer(cstart))
varbuf C.git_buf
deferC.git_buf_dispose(&buf)
runtime.LockOSThread()
deferruntime.UnlockOSThread()
ret:=C.git_repository_discover(&buf, cstart, cbool(across_fs), ceildirs)
ifret<0 {
return"", MakeGitError(ret)
}
returnC.GoString(buf.ptr), nil
}