diff --git a/blob.go b/blob.go index e8296bb..652b729 100644 --- a/blob.go +++ b/blob.go @@ -9,7 +9,6 @@ void _go_git_writestream_free(git_writestream *stream); */ import "C" import ( - "io" "reflect" "runtime" "unsafe" @@ -76,32 +75,6 @@ func (repo *Repository) CreateBlobFromBuffer(data []byte) (*Oid, error) { return newOidFromC(&id), nil } -type BlobChunkCallback func(maxLen int) ([]byte, error) - -type BlobCallbackData struct { - Callback BlobChunkCallback - Error error -} - -//export blobChunkCb -func blobChunkCb(buffer *C.char, maxLen C.size_t, handle unsafe.Pointer) int { - payload := pointerHandles.Get(handle) - data, ok := payload.(*BlobCallbackData) - if !ok { - panic("could not retrieve blob callback data") - } - - goBuf, err := data.Callback(int(maxLen)) - if err == io.EOF { - return 0 - } else if err != nil { - data.Error = err - return -1 - } - C.memcpy(unsafe.Pointer(buffer), unsafe.Pointer(&goBuf[0]), C.size_t(len(goBuf))) - return len(goBuf) -} - func (repo *Repository) CreateFromStream(hintPath string) (*BlobWriteStream, error) { var chintPath *C.char = nil var stream *C.git_writestream diff --git a/branch.go b/branch.go index d6e7a53..3985ad2 100644 --- a/branch.go +++ b/branch.go @@ -73,7 +73,7 @@ func (i *BranchIterator) ForEach(f BranchIteratorFunc) error { } } - if err != nil && IsErrorCode(err, ErrIterOver) { + if err != nil && IsErrorCode(err, ErrorCodeIterOver) { return nil } diff --git a/branch_test.go b/branch_test.go index 01a2e28..56795a4 100644 --- a/branch_test.go +++ b/branch_test.go @@ -22,7 +22,7 @@ func TestBranchIterator(t *testing.T) { t.Fatalf("expected BranchLocal, not %v", t) } b, bt, err = i.Next() - if !IsErrorCode(err, ErrIterOver) { + if !IsErrorCode(err, ErrorCodeIterOver) { t.Fatal("expected iterover") } } @@ -49,7 +49,7 @@ func TestBranchIteratorEach(t *testing.T) { } err = i.ForEach(f) - if err != nil && !IsErrorCode(err, ErrIterOver) { + if err != nil && !IsErrorCode(err, ErrorCodeIterOver) { t.Fatal(err) } diff --git a/checkout.go b/checkout.go index 76d6d69..71ccac4 100644 --- a/checkout.go +++ b/checkout.go @@ -52,7 +52,7 @@ const ( type CheckoutNotifyCallback func(why CheckoutNotifyType, path string, baseline, target, workdir DiffFile) ErrorCode type CheckoutProgressCallback func(path string, completed, total uint) ErrorCode -type CheckoutOpts struct { +type CheckoutOptions struct { Strategy CheckoutStrategy // Default will be a dry run DisableFilters bool // Don't apply filters like CRLF conversion DirMode os.FileMode // Default is 0755 @@ -66,19 +66,20 @@ type CheckoutOpts struct { Baseline *Tree } -func checkoutOptionsFromC(c *C.git_checkout_options) CheckoutOpts { - opts := CheckoutOpts{} - opts.Strategy = CheckoutStrategy(c.checkout_strategy) - opts.DisableFilters = c.disable_filters != 0 - opts.DirMode = os.FileMode(c.dir_mode) - opts.FileMode = os.FileMode(c.file_mode) - opts.FileOpenFlags = int(c.file_open_flags) - opts.NotifyFlags = CheckoutNotifyType(c.notify_flags) +func checkoutOptionsFromC(c *C.git_checkout_options) CheckoutOptions { + opts := CheckoutOptions{ + Strategy: CheckoutStrategy(c.checkout_strategy), + DisableFilters: c.disable_filters != 0, + DirMode: os.FileMode(c.dir_mode), + FileMode: os.FileMode(c.file_mode), + FileOpenFlags: int(c.file_open_flags), + NotifyFlags: CheckoutNotifyType(c.notify_flags), + } if c.notify_payload != nil { - opts.NotifyCallback = pointerHandles.Get(c.notify_payload).(*CheckoutOpts).NotifyCallback + opts.NotifyCallback = pointerHandles.Get(c.notify_payload).(*CheckoutOptions).NotifyCallback } if c.progress_payload != nil { - opts.ProgressCallback = pointerHandles.Get(c.progress_payload).(*CheckoutOpts).ProgressCallback + opts.ProgressCallback = pointerHandles.Get(c.progress_payload).(*CheckoutOptions).ProgressCallback } if c.target_directory != nil { opts.TargetDirectory = C.GoString(c.target_directory) @@ -86,12 +87,12 @@ func checkoutOptionsFromC(c *C.git_checkout_options) CheckoutOpts { return opts } -func (opts *CheckoutOpts) toC() *C.git_checkout_options { +func (opts *CheckoutOptions) toC() *C.git_checkout_options { if opts == nil { return nil } c := C.git_checkout_options{} - populateCheckoutOpts(&c, opts) + populateCheckoutOptions(&c, opts) return &c } @@ -111,7 +112,7 @@ func checkoutNotifyCallback(why C.git_checkout_notify_t, cpath *C.char, cbaselin if cworkdir != nil { workdir = diffFileFromC((*C.git_diff_file)(cworkdir)) } - opts := pointerHandles.Get(data).(*CheckoutOpts) + opts := pointerHandles.Get(data).(*CheckoutOptions) if opts.NotifyCallback == nil { return 0 } @@ -120,17 +121,17 @@ func checkoutNotifyCallback(why C.git_checkout_notify_t, cpath *C.char, cbaselin //export checkoutProgressCallback func checkoutProgressCallback(path *C.char, completed_steps, total_steps C.size_t, data unsafe.Pointer) int { - opts := pointerHandles.Get(data).(*CheckoutOpts) + opts := pointerHandles.Get(data).(*CheckoutOptions) if opts.ProgressCallback == nil { return 0 } return int(opts.ProgressCallback(C.GoString(path), uint(completed_steps), uint(total_steps))) } -// Convert the CheckoutOpts struct to the corresponding +// Convert the CheckoutOptions struct to the corresponding // C-struct. Returns a pointer to ptr, or nil if opts is nil, in order // to help with what to pass. -func populateCheckoutOpts(ptr *C.git_checkout_options, opts *CheckoutOpts) *C.git_checkout_options { +func populateCheckoutOptions(ptr *C.git_checkout_options, opts *CheckoutOptions) *C.git_checkout_options { if opts == nil { return nil } @@ -166,7 +167,7 @@ func populateCheckoutOpts(ptr *C.git_checkout_options, opts *CheckoutOpts) *C.gi return ptr } -func freeCheckoutOpts(ptr *C.git_checkout_options) { +func freeCheckoutOptions(ptr *C.git_checkout_options) { if ptr == nil { return } @@ -181,12 +182,12 @@ func freeCheckoutOpts(ptr *C.git_checkout_options) { // Updates files in the index and the working tree to match the content of // the commit pointed at by HEAD. opts may be nil. -func (v *Repository) CheckoutHead(opts *CheckoutOpts) error { +func (v *Repository) CheckoutHead(opts *CheckoutOptions) error { runtime.LockOSThread() defer runtime.UnlockOSThread() cOpts := opts.toC() - defer freeCheckoutOpts(cOpts) + defer freeCheckoutOptions(cOpts) ret := C.git_checkout_head(v.ptr, cOpts) runtime.KeepAlive(v) @@ -200,7 +201,7 @@ func (v *Repository) CheckoutHead(opts *CheckoutOpts) error { // Updates files in the working tree to match the content of the given // index. If index is nil, the repository's index will be used. opts // may be nil. -func (v *Repository) CheckoutIndex(index *Index, opts *CheckoutOpts) error { +func (v *Repository) CheckoutIndex(index *Index, opts *CheckoutOptions) error { var iptr *C.git_index = nil if index != nil { iptr = index.ptr @@ -210,7 +211,7 @@ func (v *Repository) CheckoutIndex(index *Index, opts *CheckoutOpts) error { defer runtime.UnlockOSThread() cOpts := opts.toC() - defer freeCheckoutOpts(cOpts) + defer freeCheckoutOptions(cOpts) ret := C.git_checkout_index(v.ptr, iptr, cOpts) runtime.KeepAlive(v) @@ -221,12 +222,12 @@ func (v *Repository) CheckoutIndex(index *Index, opts *CheckoutOpts) error { return nil } -func (v *Repository) CheckoutTree(tree *Tree, opts *CheckoutOpts) error { +func (v *Repository) CheckoutTree(tree *Tree, opts *CheckoutOptions) error { runtime.LockOSThread() defer runtime.UnlockOSThread() cOpts := opts.toC() - defer freeCheckoutOpts(cOpts) + defer freeCheckoutOptions(cOpts) ret := C.git_checkout_tree(v.ptr, tree.ptr, cOpts) runtime.KeepAlive(v) diff --git a/cherrypick.go b/cherrypick.go index e86e940..b80852b 100644 --- a/cherrypick.go +++ b/cherrypick.go @@ -12,7 +12,7 @@ type CherrypickOptions struct { Version uint Mainline uint MergeOpts MergeOptions - CheckoutOpts CheckoutOpts + CheckoutOpts CheckoutOptions } func cherrypickOptionsFromC(c *C.git_cherrypick_options) CherrypickOptions { @@ -41,7 +41,7 @@ func freeCherrypickOpts(ptr *C.git_cherrypick_options) { if ptr == nil { return } - freeCheckoutOpts(&ptr.checkout_opts) + freeCheckoutOptions(&ptr.checkout_opts) } func DefaultCherrypickOptions() (CherrypickOptions, error) { diff --git a/cherrypick_test.go b/cherrypick_test.go index 19a9736..06f6585 100644 --- a/cherrypick_test.go +++ b/cherrypick_test.go @@ -11,7 +11,7 @@ func checkout(t *testing.T, repo *Repository, commit *Commit) { t.Fatal(err) } - err = repo.CheckoutTree(tree, &CheckoutOpts{Strategy: CheckoutSafe}) + err = repo.CheckoutTree(tree, &CheckoutOptions{Strategy: CheckoutSafe}) if err != nil { t.Fatal(err) } diff --git a/clone.go b/clone.go index 1ff5124..b329a25 100644 --- a/clone.go +++ b/clone.go @@ -58,19 +58,19 @@ func remoteCreateCallback(cremote unsafe.Pointer, crepo unsafe.Pointer, cname, c runtime.SetFinalizer(repo, nil) if opts, ok := pointerHandles.Get(payload).(CloneOptions); ok { - remote, err := opts.RemoteCreateCallback(repo, name, url) + remote, errorCode := opts.RemoteCreateCallback(repo, name, url) // clear finalizer as the calling C function will // free the remote itself runtime.SetFinalizer(remote, nil) - if err == ErrOk && remote != nil { + if errorCode == ErrorCodeOK && remote != nil { cptr := (**C.git_remote)(cremote) *cptr = remote.ptr - } else if err == ErrOk && remote == nil { + } else if errorCode == ErrorCodeOK && remote == nil { panic("no remote created by callback") } - return C.int(err) + return C.int(errorCode) } else { panic("invalid remote create callback") } @@ -82,7 +82,7 @@ func populateCloneOptions(ptr *C.git_clone_options, opts *CloneOptions) { if opts == nil { return } - populateCheckoutOpts(&ptr.checkout_opts, opts.CheckoutOpts) + populateCheckoutOptions(&ptr.checkout_opts, opts.CheckoutOpts) populateFetchOptions(&ptr.fetch_opts, opts.FetchOptions) ptr.bare = cbool(opts.Bare) @@ -98,7 +98,7 @@ func freeCloneOptions(ptr *C.git_clone_options) { return } - freeCheckoutOpts(&ptr.checkout_opts) + freeCheckoutOptions(&ptr.checkout_opts) if ptr.remote_cb_payload != nil { pointerHandles.Untrack(ptr.remote_cb_payload) diff --git a/clone_test.go b/clone_test.go index 24c3a09..ded9847 100644 --- a/clone_test.go +++ b/clone_test.go @@ -54,10 +54,10 @@ func TestCloneWithCallback(t *testing.T) { remote, err := r.Remotes.Create(REMOTENAME, url) if err != nil { - return nil, ErrGeneric + return nil, ErrorCodeGeneric } - return remote, ErrOk + return remote, ErrorCodeOK }, } diff --git a/deprecated.go b/deprecated.go new file mode 100644 index 0000000..1e24c10 --- /dev/null +++ b/deprecated.go @@ -0,0 +1,138 @@ +package git + +/* +#include +*/ +import "C" +import ( + "unsafe" +) + +// The constants, functions, and types in this files are slated for deprecation +// in the next major version. + +// blob.go + +// BlobChunkCallback is not used. +type BlobChunkCallback func(maxLen int) ([]byte, error) + +// BlobCallbackData is not used. +type BlobCallbackData struct { + Callback BlobChunkCallback + Error error +} + +// checkout.go + +// CheckoutOpts is a deprecated alias of CheckoutOptions. +type CheckoutOpts = CheckoutOptions + +// features.go + +const ( + // FeatureHttps is a deprecated alias of FeatureHTTPS. + FeatureHttps = FeatureHTTPS + + // FeatureSsh is a deprecated alias of FeatureSSH. + FeatureSsh = FeatureSSH +) + +// git.go + +const ( + ErrClassNone = ErrorClassNone + ErrClassNoMemory = ErrorClassNoMemory + ErrClassOs = ErrorClassOS + ErrClassInvalid = ErrorClassInvalid + ErrClassReference = ErrorClassReference + ErrClassZlib = ErrorClassZlib + ErrClassRepository = ErrorClassRepository + ErrClassConfig = ErrorClassConfig + ErrClassRegex = ErrorClassRegex + ErrClassOdb = ErrorClassOdb + ErrClassIndex = ErrorClassIndex + ErrClassObject = ErrorClassObject + ErrClassNet = ErrorClassNet + ErrClassTag = ErrorClassTag + ErrClassTree = ErrorClassTree + ErrClassIndexer = ErrorClassIndexer + ErrClassSSL = ErrorClassSSL + ErrClassSubmodule = ErrorClassSubmodule + ErrClassThread = ErrorClassThread + ErrClassStash = ErrorClassStash + ErrClassCheckout = ErrorClassCheckout + ErrClassFetchHead = ErrorClassFetchHead + ErrClassMerge = ErrorClassMerge + ErrClassSsh = ErrorClassSSH + ErrClassFilter = ErrorClassFilter + ErrClassRevert = ErrorClassRevert + ErrClassCallback = ErrorClassCallback + ErrClassRebase = ErrorClassRebase + ErrClassPatch = ErrorClassPatch +) + +const ( + ErrOk = ErrorCodeOK + ErrGeneric = ErrorCodeGeneric + ErrNotFound = ErrorCodeNotFound + ErrExists = ErrorCodeExists + ErrAmbiguous = ErrorCodeAmbiguous + ErrAmbigious = ErrorCodeAmbiguous + ErrBuffs = ErrorCodeBuffs + ErrUser = ErrorCodeUser + ErrBareRepo = ErrorCodeBareRepo + ErrUnbornBranch = ErrorCodeUnbornBranch + ErrUnmerged = ErrorCodeUnmerged + ErrNonFastForward = ErrorCodeNonFastForward + ErrInvalidSpec = ErrorCodeInvalidSpec + ErrConflict = ErrorCodeConflict + ErrLocked = ErrorCodeLocked + ErrModified = ErrorCodeModified + ErrAuth = ErrorCodeAuth + ErrCertificate = ErrorCodeCertificate + ErrApplied = ErrorCodeApplied + ErrPeel = ErrorCodePeel + ErrEOF = ErrorCodeEOF + ErrUncommitted = ErrorCodeUncommitted + ErrDirectory = ErrorCodeDirectory + ErrMergeConflict = ErrorCodeMergeConflict + ErrPassthrough = ErrorCodePassthrough + ErrIterOver = ErrorCodeIterOver +) + +// index.go + +// IndexAddOpts is a deprecated alias of IndexAddOption. +type IndexAddOpts = IndexAddOption + +// IndexStageOpts is a deprecated alias of IndexStageState. +type IndexStageOpts = IndexStageState + +// submodule.go + +// SubmoduleCbk is a deprecated alias of SubmoduleCallback. +type SubmoduleCbk = SubmoduleCallback + +// SubmoduleVisitor is not used. +func SubmoduleVisitor(csub unsafe.Pointer, name *C.char, handle unsafe.Pointer) C.int { + sub := &Submodule{(*C.git_submodule)(csub), nil} + + callback, ok := pointerHandles.Get(handle).(SubmoduleCallback) + if !ok { + panic("invalid submodule visitor callback") + } + return (C.int)(callback(sub, C.GoString(name))) +} + +// tree.go + +// CallbackGitTreeWalk is not used. +func CallbackGitTreeWalk(_root *C.char, entry *C.git_tree_entry, ptr unsafe.Pointer) C.int { + root := C.GoString(_root) + + if callback, ok := pointerHandles.Get(ptr).(TreeWalkCallback); ok { + return C.int(callback(root, newTreeEntry(entry))) + } else { + panic("invalid treewalk callback") + } +} diff --git a/errorclass_string.go b/errorclass_string.go new file mode 100644 index 0000000..1223442 --- /dev/null +++ b/errorclass_string.go @@ -0,0 +1,63 @@ +// Code generated by "stringer -type ErrorClass -trimprefix ErrorClass -tags static"; DO NOT EDIT. + +package git + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[ErrorClassNone-0] + _ = x[ErrorClassNoMemory-1] + _ = x[ErrorClassOS-2] + _ = x[ErrorClassInvalid-3] + _ = x[ErrorClassReference-4] + _ = x[ErrorClassZlib-5] + _ = x[ErrorClassRepository-6] + _ = x[ErrorClassConfig-7] + _ = x[ErrorClassRegex-8] + _ = x[ErrorClassOdb-9] + _ = x[ErrorClassIndex-10] + _ = x[ErrorClassObject-11] + _ = x[ErrorClassNet-12] + _ = x[ErrorClassTag-13] + _ = x[ErrorClassTree-14] + _ = x[ErrorClassIndexer-15] + _ = x[ErrorClassSSL-16] + _ = x[ErrorClassSubmodule-17] + _ = x[ErrorClassThread-18] + _ = x[ErrorClassStash-19] + _ = x[ErrorClassCheckout-20] + _ = x[ErrorClassFetchHead-21] + _ = x[ErrorClassMerge-22] + _ = x[ErrorClassSSH-23] + _ = x[ErrorClassFilter-24] + _ = x[ErrorClassRevert-25] + _ = x[ErrorClassCallback-26] + _ = x[ErrorClassRebase-29] + _ = x[ErrorClassPatch-31] +} + +const ( + _ErrorClass_name_0 = "NoneNoMemoryOSInvalidReferenceZlibRepositoryConfigRegexOdbIndexObjectNetTagTreeIndexerSSLSubmoduleThreadStashCheckoutFetchHeadMergeSSHFilterRevertCallback" + _ErrorClass_name_1 = "Rebase" + _ErrorClass_name_2 = "Patch" +) + +var ( + _ErrorClass_index_0 = [...]uint8{0, 4, 12, 14, 21, 30, 34, 44, 50, 55, 58, 63, 69, 72, 75, 79, 86, 89, 98, 104, 109, 117, 126, 131, 134, 140, 146, 154} +) + +func (i ErrorClass) String() string { + switch { + case 0 <= i && i <= 26: + return _ErrorClass_name_0[_ErrorClass_index_0[i]:_ErrorClass_index_0[i+1]] + case i == 29: + return _ErrorClass_name_1 + case i == 31: + return _ErrorClass_name_2 + default: + return "ErrorClass(" + strconv.FormatInt(int64(i), 10) + ")" + } +} diff --git a/errorcode_string.go b/errorcode_string.go new file mode 100644 index 0000000..b15214e --- /dev/null +++ b/errorcode_string.go @@ -0,0 +1,67 @@ +// Code generated by "stringer -type ErrorCode -trimprefix ErrorCode -tags static"; DO NOT EDIT. + +package git + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[ErrorCodeOK-0] + _ = x[ErrorCodeGeneric - -1] + _ = x[ErrorCodeNotFound - -3] + _ = x[ErrorCodeExists - -4] + _ = x[ErrorCodeAmbiguous - -5] + _ = x[ErrorCodeBuffs - -6] + _ = x[ErrorCodeUser - -7] + _ = x[ErrorCodeBareRepo - -8] + _ = x[ErrorCodeUnbornBranch - -9] + _ = x[ErrorCodeUnmerged - -10] + _ = x[ErrorCodeNonFastForward - -11] + _ = x[ErrorCodeInvalidSpec - -12] + _ = x[ErrorCodeConflict - -13] + _ = x[ErrorCodeLocked - -14] + _ = x[ErrorCodeModified - -15] + _ = x[ErrorCodeAuth - -16] + _ = x[ErrorCodeCertificate - -17] + _ = x[ErrorCodeApplied - -18] + _ = x[ErrorCodePeel - -19] + _ = x[ErrorCodeEOF - -20] + _ = x[ErrorCodeInvalid - -21] + _ = x[ErrorCodeUncommitted - -22] + _ = x[ErrorCodeDirectory - -23] + _ = x[ErrorCodeMergeConflict - -24] + _ = x[ErrorCodePassthrough - -30] + _ = x[ErrorCodeIterOver - -31] + _ = x[ErrorCodeRetry - -32] + _ = x[ErrorCodeMismatch - -33] +} + +const ( + _ErrorCode_name_0 = "MismatchRetryIterOverPassthrough" + _ErrorCode_name_1 = "MergeConflictDirectoryUncommittedInvalidEOFPeelAppliedCertificateAuthModifiedLockedConflictInvalidSpecNonFastForwardUnmergedUnbornBranchBareRepoUserBuffsAmbiguousExistsNotFound" + _ErrorCode_name_2 = "GenericOK" +) + +var ( + _ErrorCode_index_0 = [...]uint8{0, 8, 13, 21, 32} + _ErrorCode_index_1 = [...]uint8{0, 13, 22, 33, 40, 43, 47, 54, 65, 69, 77, 83, 91, 102, 116, 124, 136, 144, 148, 153, 162, 168, 176} + _ErrorCode_index_2 = [...]uint8{0, 7, 9} +) + +func (i ErrorCode) String() string { + switch { + case -33 <= i && i <= -30: + i -= -33 + return _ErrorCode_name_0[_ErrorCode_index_0[i]:_ErrorCode_index_0[i+1]] + case -24 <= i && i <= -3: + i -= -24 + return _ErrorCode_name_1[_ErrorCode_index_1[i]:_ErrorCode_index_1[i+1]] + case -1 <= i && i <= 0: + i -= -1 + return _ErrorCode_name_2[_ErrorCode_index_2[i]:_ErrorCode_index_2[i+1]] + default: + return "ErrorCode(" + strconv.FormatInt(int64(i), 10) + ")" + } +} diff --git a/features.go b/features.go index f6474a0..a9f81a1 100644 --- a/features.go +++ b/features.go @@ -12,10 +12,10 @@ const ( FeatureThreads Feature = C.GIT_FEATURE_THREADS // libgit2 was built with HTTPS support built-in - FeatureHttps Feature = C.GIT_FEATURE_HTTPS + FeatureHTTPS Feature = C.GIT_FEATURE_HTTPS // libgit2 was build with SSH support built-in - FeatureSsh Feature = C.GIT_FEATURE_SSH + FeatureSSH Feature = C.GIT_FEATURE_SSH // libgit2 was built with nanosecond support for files FeatureNSec Feature = C.GIT_FEATURE_NSEC diff --git a/git.go b/git.go index d833505..34086a9 100644 --- a/git.go +++ b/git.go @@ -17,98 +17,102 @@ import ( type ErrorClass int const ( - ErrClassNone ErrorClass = C.GITERR_NONE - ErrClassNoMemory ErrorClass = C.GITERR_NOMEMORY - ErrClassOs ErrorClass = C.GITERR_OS - ErrClassInvalid ErrorClass = C.GITERR_INVALID - ErrClassReference ErrorClass = C.GITERR_REFERENCE - ErrClassZlib ErrorClass = C.GITERR_ZLIB - ErrClassRepository ErrorClass = C.GITERR_REPOSITORY - ErrClassConfig ErrorClass = C.GITERR_CONFIG - ErrClassRegex ErrorClass = C.GITERR_REGEX - ErrClassOdb ErrorClass = C.GITERR_ODB - ErrClassIndex ErrorClass = C.GITERR_INDEX - ErrClassObject ErrorClass = C.GITERR_OBJECT - ErrClassNet ErrorClass = C.GITERR_NET - ErrClassTag ErrorClass = C.GITERR_TAG - ErrClassTree ErrorClass = C.GITERR_TREE - ErrClassIndexer ErrorClass = C.GITERR_INDEXER - ErrClassSSL ErrorClass = C.GITERR_SSL - ErrClassSubmodule ErrorClass = C.GITERR_SUBMODULE - ErrClassThread ErrorClass = C.GITERR_THREAD - ErrClassStash ErrorClass = C.GITERR_STASH - ErrClassCheckout ErrorClass = C.GITERR_CHECKOUT - ErrClassFetchHead ErrorClass = C.GITERR_FETCHHEAD - ErrClassMerge ErrorClass = C.GITERR_MERGE - ErrClassSsh ErrorClass = C.GITERR_SSH - ErrClassFilter ErrorClass = C.GITERR_FILTER - ErrClassRevert ErrorClass = C.GITERR_REVERT - ErrClassCallback ErrorClass = C.GITERR_CALLBACK - ErrClassRebase ErrorClass = C.GITERR_REBASE + ErrorClassNone ErrorClass = C.GITERR_NONE + ErrorClassNoMemory ErrorClass = C.GITERR_NOMEMORY + ErrorClassOS ErrorClass = C.GITERR_OS + ErrorClassInvalid ErrorClass = C.GITERR_INVALID + ErrorClassReference ErrorClass = C.GITERR_REFERENCE + ErrorClassZlib ErrorClass = C.GITERR_ZLIB + ErrorClassRepository ErrorClass = C.GITERR_REPOSITORY + ErrorClassConfig ErrorClass = C.GITERR_CONFIG + ErrorClassRegex ErrorClass = C.GITERR_REGEX + ErrorClassOdb ErrorClass = C.GITERR_ODB + ErrorClassIndex ErrorClass = C.GITERR_INDEX + ErrorClassObject ErrorClass = C.GITERR_OBJECT + ErrorClassNet ErrorClass = C.GITERR_NET + ErrorClassTag ErrorClass = C.GITERR_TAG + ErrorClassTree ErrorClass = C.GITERR_TREE + ErrorClassIndexer ErrorClass = C.GITERR_INDEXER + ErrorClassSSL ErrorClass = C.GITERR_SSL + ErrorClassSubmodule ErrorClass = C.GITERR_SUBMODULE + ErrorClassThread ErrorClass = C.GITERR_THREAD + ErrorClassStash ErrorClass = C.GITERR_STASH + ErrorClassCheckout ErrorClass = C.GITERR_CHECKOUT + ErrorClassFetchHead ErrorClass = C.GITERR_FETCHHEAD + ErrorClassMerge ErrorClass = C.GITERR_MERGE + ErrorClassSSH ErrorClass = C.GITERR_SSH + ErrorClassFilter ErrorClass = C.GITERR_FILTER + ErrorClassRevert ErrorClass = C.GITERR_REVERT + ErrorClassCallback ErrorClass = C.GITERR_CALLBACK + ErrorClassRebase ErrorClass = C.GITERR_REBASE + ErrorClassPatch ErrorClass = C.GITERR_PATCH ) type ErrorCode int const ( + // ErrorCodeOK indicates that the operation completed successfully. + ErrorCodeOK ErrorCode = C.GIT_OK - // No error - ErrOk ErrorCode = C.GIT_OK + // ErrorCodeGeneric represents a generic error. + ErrorCodeGeneric ErrorCode = C.GIT_ERROR + // ErrorCodeNotFound represents that the requested object could not be found + ErrorCodeNotFound ErrorCode = C.GIT_ENOTFOUND + // ErrorCodeExists represents that the object exists preventing operation. + ErrorCodeExists ErrorCode = C.GIT_EEXISTS + // ErrorCodeAmbiguous represents that more than one object matches. + ErrorCodeAmbiguous ErrorCode = C.GIT_EAMBIGUOUS + // ErrorCodeBuffs represents that the output buffer is too short to hold data. + ErrorCodeBuffs ErrorCode = C.GIT_EBUFS - // Generic error - ErrGeneric ErrorCode = C.GIT_ERROR - // Requested object could not be found - ErrNotFound ErrorCode = C.GIT_ENOTFOUND - // Object exists preventing operation - ErrExists ErrorCode = C.GIT_EEXISTS - // More than one object matches - ErrAmbiguous ErrorCode = C.GIT_EAMBIGUOUS - // (backwards compatibility misspelling) - ErrAmbigious ErrorCode = C.GIT_EAMBIGUOUS - // Output buffer too short to hold data - ErrBuffs ErrorCode = C.GIT_EBUFS - - // GIT_EUSER is a special error that is never generated by libgit2 + // 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. - ErrUser ErrorCode = C.GIT_EUSER + ErrorCodeUser ErrorCode = C.GIT_EUSER - // Operation not allowed on bare repository - ErrBareRepo ErrorCode = C.GIT_EBAREREPO - // HEAD refers to branch with no commits - ErrUnbornBranch ErrorCode = C.GIT_EUNBORNBRANCH - // Merge in progress prevented operation - ErrUnmerged ErrorCode = C.GIT_EUNMERGED - // Reference was not fast-forwardable - ErrNonFastForward ErrorCode = C.GIT_ENONFASTFORWARD - // Name/ref spec was not in a valid format - ErrInvalidSpec ErrorCode = C.GIT_EINVALIDSPEC - // Checkout conflicts prevented operation - ErrConflict ErrorCode = C.GIT_ECONFLICT - // Lock file prevented operation - ErrLocked ErrorCode = C.GIT_ELOCKED - // Reference value does not match expected - ErrModified ErrorCode = C.GIT_EMODIFIED - // Authentication failed - ErrAuth ErrorCode = C.GIT_EAUTH - // Server certificate is invalid - ErrCertificate ErrorCode = C.GIT_ECERTIFICATE - // Patch/merge has already been applied - ErrApplied ErrorCode = C.GIT_EAPPLIED - // The requested peel operation is not possible - ErrPeel ErrorCode = C.GIT_EPEEL - // Unexpected EOF - ErrEOF ErrorCode = C.GIT_EEOF - // Uncommitted changes in index prevented operation - ErrUncommitted ErrorCode = C.GIT_EUNCOMMITTED - // The operation is not valid for a directory - ErrDirectory ErrorCode = C.GIT_EDIRECTORY - // A merge conflict exists and cannot continue - ErrMergeConflict ErrorCode = C.GIT_EMERGECONFLICT + // ErrorCodeBareRepo represents that the operation not allowed on bare repository + ErrorCodeBareRepo ErrorCode = C.GIT_EBAREREPO + // ErrorCodeUnbornBranch represents that HEAD refers to branch with no commits. + ErrorCodeUnbornBranch ErrorCode = C.GIT_EUNBORNBRANCH + // ErrorCodeUnmerged represents that a merge in progress prevented operation. + ErrorCodeUnmerged ErrorCode = C.GIT_EUNMERGED + // ErrorCodeNonFastForward represents that the reference was not fast-forwardable. + ErrorCodeNonFastForward ErrorCode = C.GIT_ENONFASTFORWARD + // ErrorCodeInvalidSpec represents that the name/ref spec was not in a valid format. + ErrorCodeInvalidSpec ErrorCode = C.GIT_EINVALIDSPEC + // ErrorCodeConflict represents that checkout conflicts prevented operation. + ErrorCodeConflict ErrorCode = C.GIT_ECONFLICT + // ErrorCodeLocked represents that lock file prevented operation. + ErrorCodeLocked ErrorCode = C.GIT_ELOCKED + // ErrorCodeModified represents that the reference value does not match expected. + ErrorCodeModified ErrorCode = C.GIT_EMODIFIED + // ErrorCodeAuth represents that the authentication failed. + ErrorCodeAuth ErrorCode = C.GIT_EAUTH + // ErrorCodeCertificate represents that the server certificate is invalid. + ErrorCodeCertificate ErrorCode = C.GIT_ECERTIFICATE + // ErrorCodeApplied represents that the patch/merge has already been applied. + ErrorCodeApplied ErrorCode = C.GIT_EAPPLIED + // ErrorCodePeel represents that the requested peel operation is not possible. + ErrorCodePeel ErrorCode = C.GIT_EPEEL + // ErrorCodeEOF represents an unexpected EOF. + ErrorCodeEOF ErrorCode = C.GIT_EEOF + // ErrorCodeInvalid represents an invalid operation or input. + ErrorCodeInvalid ErrorCode = C.GIT_EINVALID + // ErrorCodeUIncommitted represents that uncommitted changes in index prevented operation. + ErrorCodeUncommitted ErrorCode = C.GIT_EUNCOMMITTED + // ErrorCodeDirectory represents that the operation is not valid for a directory. + ErrorCodeDirectory ErrorCode = C.GIT_EDIRECTORY + // ErrorCodeMergeConflict represents that a merge conflict exists and cannot continue. + ErrorCodeMergeConflict ErrorCode = C.GIT_EMERGECONFLICT - // Internal only - ErrPassthrough ErrorCode = C.GIT_PASSTHROUGH - // Signals end of iteration with iterator - ErrIterOver ErrorCode = C.GIT_ITEROVER + // ErrorCodePassthrough represents that a user-configured callback refused to act. + ErrorCodePassthrough ErrorCode = C.GIT_PASSTHROUGH + // ErrorCodeIterOver signals end of iteration with iterator. + ErrorCodeIterOver ErrorCode = C.GIT_ITEROVER + // ErrorCodeRetry is an internal-only error code. + ErrorCodeRetry ErrorCode = C.GIT_RETRY + // ErrorCodeMismatch represents a hashsum mismatch in object. + ErrorCodeMismatch ErrorCode = C.GIT_EMISMATCH ) var ( @@ -198,7 +202,7 @@ func NewOid(s string) (*Oid, error) { } if len(slice) != 20 { - return nil, &GitError{"Invalid Oid", ErrClassNone, ErrGeneric} + return nil, &GitError{"Invalid Oid", ErrorClassNone, ErrGeneric} } copy(o[:], slice[:20]) @@ -266,7 +270,6 @@ func (e GitError) Error() string { } func IsErrorClass(err error, c ErrorClass) bool { - if err == nil { return false } @@ -286,20 +289,23 @@ func IsErrorCode(err error, c ErrorCode) bool { return false } -func MakeGitError(errorCode C.int) error { - +func MakeGitError(c C.int) error { var errMessage string var errClass ErrorClass - if errorCode != C.GIT_ITEROVER { + errorCode := ErrorCode(c) + if errorCode != ErrorCodeIterOver { err := C.giterr_last() if err != nil { errMessage = C.GoString(err.message) errClass = ErrorClass(err.klass) } else { - errClass = ErrClassInvalid + errClass = ErrorClassInvalid } } - return &GitError{errMessage, errClass, ErrorCode(errorCode)} + if errMessage == "" { + errMessage = errorCode.String() + } + return &GitError{errMessage, errClass, errorCode} } func MakeGitError2(err int) error { diff --git a/git_test.go b/git_test.go index 91ade73..1bd311a 100644 --- a/git_test.go +++ b/git_test.go @@ -45,16 +45,16 @@ func createBareTestRepo(t *testing.T) *Repository { return repo } -// commitOpts contains any extra options for creating commits in the seed repo -type commitOpts struct { +// commitOptions contains any extra options for creating commits in the seed repo +type commitOptions struct { CommitSigningCallback } func seedTestRepo(t *testing.T, repo *Repository) (*Oid, *Oid) { - return seedTestRepoOpt(t, repo, commitOpts{}) + return seedTestRepoOpt(t, repo, commitOptions{}) } -func seedTestRepoOpt(t *testing.T, repo *Repository, opts commitOpts) (*Oid, *Oid) { +func seedTestRepoOpt(t *testing.T, repo *Repository, opts commitOptions) (*Oid, *Oid) { loc, err := time.LoadLocation("Europe/Berlin") checkFatal(t, err) sig := &Signature{ @@ -155,7 +155,7 @@ func TestOidZero(t *testing.T) { func TestEmptyOid(t *testing.T) { t.Parallel() _, err := NewOid("") - if err == nil || !IsErrorCode(err, ErrGeneric) { + if err == nil || !IsErrorCode(err, ErrorCodeGeneric) { t.Fatal("Should have returned invalid error") } } diff --git a/index.go b/index.go index 626e649..7173ae0 100644 --- a/index.go +++ b/index.go @@ -17,31 +17,33 @@ import ( type IndexMatchedPathCallback func(string, string) int -type IndexAddOpts uint +// IndexAddOption is a set of flags for APIs that add files matching pathspec. +type IndexAddOption uint const ( - IndexAddDefault IndexAddOpts = C.GIT_INDEX_ADD_DEFAULT - IndexAddForce IndexAddOpts = C.GIT_INDEX_ADD_FORCE - IndexAddDisablePathspecMatch IndexAddOpts = C.GIT_INDEX_ADD_DISABLE_PATHSPEC_MATCH - IndexAddCheckPathspec IndexAddOpts = C.GIT_INDEX_ADD_CHECK_PATHSPEC + IndexAddDefault IndexAddOption = C.GIT_INDEX_ADD_DEFAULT + IndexAddForce IndexAddOption = C.GIT_INDEX_ADD_FORCE + IndexAddDisablePathspecMatch IndexAddOption = C.GIT_INDEX_ADD_DISABLE_PATHSPEC_MATCH + IndexAddCheckPathspec IndexAddOption = C.GIT_INDEX_ADD_CHECK_PATHSPEC ) -type IndexStageOpts int +// IndexStageState indicates the state of the git index. +type IndexStageState int const ( // IndexStageAny matches any index stage. // // Some index APIs take a stage to match; pass this value to match // any entry matching the path regardless of stage. - IndexStageAny IndexStageOpts = C.GIT_INDEX_STAGE_ANY + IndexStageAny IndexStageState = C.GIT_INDEX_STAGE_ANY // IndexStageNormal is a normal staged file in the index. - IndexStageNormal IndexStageOpts = C.GIT_INDEX_STAGE_NORMAL + IndexStageNormal IndexStageState = C.GIT_INDEX_STAGE_NORMAL // IndexStageAncestor is the ancestor side of a conflict. - IndexStageAncestor IndexStageOpts = C.GIT_INDEX_STAGE_ANCESTOR + IndexStageAncestor IndexStageState = C.GIT_INDEX_STAGE_ANCESTOR // IndexStageOurs is the "ours" side of a conflict. - IndexStageOurs IndexStageOpts = C.GIT_INDEX_STAGE_OURS + IndexStageOurs IndexStageState = C.GIT_INDEX_STAGE_OURS // IndexStageTheirs is the "theirs" side of a conflict. - IndexStageTheirs IndexStageOpts = C.GIT_INDEX_STAGE_THEIRS + IndexStageTheirs IndexStageState = C.GIT_INDEX_STAGE_THEIRS ) type Index struct { @@ -219,7 +221,7 @@ func (v *Index) AddFromBuffer(entry *IndexEntry, buffer []byte) error { return nil } -func (v *Index) AddAll(pathspecs []string, flags IndexAddOpts, callback IndexMatchedPathCallback) error { +func (v *Index) AddAll(pathspecs []string, flags IndexAddOption, callback IndexMatchedPathCallback) error { cpathspecs := C.git_strarray{} cpathspecs.count = C.size_t(len(pathspecs)) cpathspecs.strings = makeCStringsFromStrings(pathspecs) diff --git a/indexer_test.go b/indexer_test.go index 1b65c95..70b9f76 100644 --- a/indexer_test.go +++ b/indexer_test.go @@ -35,7 +35,7 @@ func TestIndexerOutOfOrder(t *testing.T) { var finalStats TransferProgress idx, err := NewIndexer(tmpPath, nil, func(stats TransferProgress) ErrorCode { finalStats = stats - return ErrOk + return ErrorCodeOK }) checkFatal(t, err) defer idx.Free() diff --git a/mempack_test.go b/mempack_test.go index 3e31dcf..9bbfea2 100644 --- a/mempack_test.go +++ b/mempack_test.go @@ -53,7 +53,7 @@ func TestMempack(t *testing.T) { if err == nil { t.Errorf("object %s unexpectedly found", obj.Id().String()) obj.Free() - } else if !IsErrorCode(err, ErrNotFound) { + } else if !IsErrorCode(err, ErrorCodeNotFound) { t.Errorf("unexpected error %v", err) } } diff --git a/merge.go b/merge.go index da1c3d6..064ca59 100644 --- a/merge.go +++ b/merge.go @@ -195,20 +195,20 @@ const ( MergeFileFavorUnion MergeFileFavor = C.GIT_MERGE_FILE_FAVOR_UNION ) -func (r *Repository) Merge(theirHeads []*AnnotatedCommit, mergeOptions *MergeOptions, checkoutOptions *CheckoutOpts) error { +func (r *Repository) Merge(theirHeads []*AnnotatedCommit, mergeOptions *MergeOptions, checkoutOptions *CheckoutOptions) error { runtime.LockOSThread() defer runtime.UnlockOSThread() cMergeOpts := mergeOptions.toC() - cCheckoutOpts := checkoutOptions.toC() - defer freeCheckoutOpts(cCheckoutOpts) + cCheckoutOptions := checkoutOptions.toC() + defer freeCheckoutOptions(cCheckoutOptions) gmerge_head_array := make([]*C.git_annotated_commit, len(theirHeads)) for i := 0; i < len(theirHeads); i++ { gmerge_head_array[i] = theirHeads[i].ptr } ptr := unsafe.Pointer(&gmerge_head_array[0]) - err := C.git_merge(r.ptr, (**C.git_annotated_commit)(ptr), C.size_t(len(theirHeads)), cMergeOpts, cCheckoutOpts) + err := C.git_merge(r.ptr, (**C.git_annotated_commit)(ptr), C.size_t(len(theirHeads)), cMergeOpts, cCheckoutOptions) runtime.KeepAlive(theirHeads) if err < 0 { return MakeGitError(err) diff --git a/note_test.go b/note_test.go index 9f64eb8..f0c9c53 100644 --- a/note_test.go +++ b/note_test.go @@ -49,7 +49,7 @@ func TestNoteIterator(t *testing.T) { for { noteId, commitId, err := iter.Next() if err != nil { - if !IsErrorCode(err, ErrIterOver) { + if !IsErrorCode(err, ErrorCodeIterOver) { checkFatal(t, err) } break diff --git a/object.go b/object.go index 5505e35..e7d3890 100644 --- a/object.go +++ b/object.go @@ -201,13 +201,13 @@ func (o *Object) Free() { // Peel recursively peels an object until an object of the specified type is met. // -// If the query cannot be satisfied due to the object model, ErrInvalidSpec +// If the query cannot be satisfied due to the object model, ErrorCodeInvalidSpec // will be returned (e.g. trying to peel a blob to a tree). // // If you pass ObjectAny as the target type, then the object will be peeled // until the type changes. A tag will be peeled until the referenced object // is no longer a tag, and a commit will be peeled to a tree. Any other object -// type will return ErrInvalidSpec. +// type will return ErrorCodeInvalidSpec. // // If peeling a tag we discover an object which cannot be peeled to the target // type due to the object model, an error will be returned. diff --git a/object_test.go b/object_test.go index 4932dd2..3b602b8 100644 --- a/object_test.go +++ b/object_test.go @@ -153,8 +153,8 @@ func TestObjectPeel(t *testing.T) { obj, err = commit.Peel(ObjectTag) - if !IsErrorCode(err, ErrInvalidSpec) { - t.Fatalf("Wrong error when peeling a commit to a tag, expected ErrInvalidSpec, have %v", err) + if !IsErrorCode(err, ErrorCodeInvalidSpec) { + t.Fatalf("Wrong error when peeling a commit to a tag, expected ErrorCodeInvalidSpec, have %v", err) } tree, err := repo.LookupTree(treeID) @@ -162,8 +162,8 @@ func TestObjectPeel(t *testing.T) { obj, err = tree.Peel(ObjectAny) - if !IsErrorCode(err, ErrInvalidSpec) { - t.Fatalf("Wrong error when peeling a tree, expected ErrInvalidSpec, have %v", err) + if !IsErrorCode(err, ErrorCodeInvalidSpec) { + t.Fatalf("Wrong error when peeling a tree, expected ErrorCodeInvalidSpec, have %v", err) } entry := tree.EntryByName("README") @@ -173,8 +173,8 @@ func TestObjectPeel(t *testing.T) { obj, err = blob.Peel(ObjectAny) - if !IsErrorCode(err, ErrInvalidSpec) { - t.Fatalf("Wrong error when peeling a blob, expected ErrInvalidSpec, have %v", err) + if !IsErrorCode(err, ErrorCodeInvalidSpec) { + t.Fatalf("Wrong error when peeling a blob, expected ErrorCodeInvalidSpec, have %v", err) } tagID := createTestTag(t, repo, commit) diff --git a/odb_test.go b/odb_test.go index d79afa1..cb3ab55 100644 --- a/odb_test.go +++ b/odb_test.go @@ -169,7 +169,7 @@ func TestOdbWritepack(t *testing.T) { var finalStats TransferProgress writepack, err := odb.NewWritePack(func(stats TransferProgress) ErrorCode { finalStats = stats - return ErrOk + return ErrorCodeOK }) checkFatal(t, err) defer writepack.Free() diff --git a/rebase.go b/rebase.go index d29e183..2c13fad 100644 --- a/rebase.go +++ b/rebase.go @@ -76,7 +76,7 @@ type RebaseOptions struct { InMemory int RewriteNotesRef string MergeOptions MergeOptions - CheckoutOptions CheckoutOpts + CheckoutOptions CheckoutOptions } // DefaultRebaseOptions returns a RebaseOptions with default values. diff --git a/rebase_test.go b/rebase_test.go index c7deef6..bd035d2 100644 --- a/rebase_test.go +++ b/rebase_test.go @@ -33,12 +33,12 @@ func TestRebaseAbort(t *testing.T) { seedTestRepo(t, repo) // Setup a repo with 2 branches and a different tree - err := setupRepoForRebase(repo, masterCommit, branchName, commitOpts{}) + err := setupRepoForRebase(repo, masterCommit, branchName, commitOptions{}) checkFatal(t, err) // Create several commits in emile for _, commit := range emileCommits { - _, err = commitSomething(repo, commit, commit, commitOpts{}) + _, err = commitSomething(repo, commit, commit, commitOptions{}) checkFatal(t, err) } @@ -94,12 +94,12 @@ func TestRebaseNoConflicts(t *testing.T) { } // Setup a repo with 2 branches and a different tree - err = setupRepoForRebase(repo, masterCommit, branchName, commitOpts{}) + err = setupRepoForRebase(repo, masterCommit, branchName, commitOptions{}) checkFatal(t, err) // Create several commits in emile for _, commit := range emileCommits { - _, err = commitSomething(repo, commit, commit, commitOpts{}) + _, err = commitSomething(repo, commit, commit, commitOptions{}) checkFatal(t, err) } @@ -133,7 +133,7 @@ func TestRebaseNoConflicts(t *testing.T) { } // Utils -func setupRepoForRebase(repo *Repository, masterCommit, branchName string, opts commitOpts) error { +func setupRepoForRebase(repo *Repository, masterCommit, branchName string, commitOpts commitOptions) error { // Create a new branch from master err := createBranch(repo, branchName) if err != nil { @@ -141,7 +141,7 @@ func setupRepoForRebase(repo *Repository, masterCommit, branchName string, opts } // Create a commit in master - _, err = commitSomething(repo, masterCommit, masterCommit, opts) + _, err = commitSomething(repo, masterCommit, masterCommit, commitOpts) if err != nil { return err } @@ -160,7 +160,7 @@ func setupRepoForRebase(repo *Repository, masterCommit, branchName string, opts return nil } -func performRebaseOnto(repo *Repository, branch string, opts *RebaseOptions) (*Rebase, error) { +func performRebaseOnto(repo *Repository, branch string, rebaseOpts *RebaseOptions) (*Rebase, error) { master, err := repo.LookupBranch(branch, BranchLocal) if err != nil { return nil, err @@ -174,7 +174,7 @@ func performRebaseOnto(repo *Repository, branch string, opts *RebaseOptions) (*R defer onto.Free() // Init rebase - rebase, err := repo.InitRebase(nil, nil, onto, opts) + rebase, err := repo.InitRebase(nil, nil, onto, rebaseOpts) if err != nil { return nil, err } @@ -275,7 +275,7 @@ func headTree(repo *Repository) (*Tree, error) { return tree, nil } -func commitSomething(repo *Repository, something, content string, commitOpts commitOpts) (*Oid, error) { +func commitSomething(repo *Repository, something, content string, commitOpts commitOptions) (*Oid, error) { headCommit, err := headCommit(repo) if err != nil { return nil, err @@ -348,10 +348,10 @@ func commitSomething(repo *Repository, something, content string, commitOpts com } } - opts := &CheckoutOpts{ + checkoutOpts := &CheckoutOptions{ Strategy: CheckoutRemoveUntracked | CheckoutForce, } - err = repo.CheckoutIndex(index, opts) + err = repo.CheckoutIndex(index, checkoutOpts) if err != nil { return nil, err } diff --git a/reference.go b/reference.go index 3288c27..02022a4 100644 --- a/reference.go +++ b/reference.go @@ -424,7 +424,7 @@ func (i *ReferenceIterator) Names() *ReferenceNameIterator { } // NextName retrieves the next reference name. If the iteration is over, -// the returned error is git.ErrIterOver +// the returned error code is git.ErrorCodeIterOver func (v *ReferenceNameIterator) Next() (string, error) { var ptr *C.char @@ -440,7 +440,7 @@ func (v *ReferenceNameIterator) Next() (string, error) { } // Next retrieves the next reference. If the iterationis over, the -// returned error is git.ErrIterOver +// returned error code is git.ErrorCodeIterOver func (v *ReferenceIterator) Next() (*Reference, error) { var ptr *C.git_reference @@ -470,7 +470,7 @@ func (v *ReferenceIterator) Free() { C.git_reference_iterator_free(v.ptr) } -// ReferenceIsValidName ensures the reference name is well-formed. +// ReferenceIsValidName returns whether the reference name is well-formed. // // Valid reference names must follow one of two patterns: // @@ -483,10 +483,8 @@ func (v *ReferenceIterator) Free() { func ReferenceIsValidName(name string) bool { cname := C.CString(name) defer C.free(unsafe.Pointer(cname)) - if C.git_reference_is_valid_name(cname) == 1 { - return true - } - return false + + return C.git_reference_is_valid_name(cname) == 1 } const ( diff --git a/reference_test.go b/reference_test.go index e42db41..285adb5 100644 --- a/reference_test.go +++ b/reference_test.go @@ -106,7 +106,7 @@ func TestReferenceIterator(t *testing.T) { list = append(list, name) name, err = nameIter.Next() } - if !IsErrorCode(err, ErrIterOver) { + if !IsErrorCode(err, ErrorCodeIterOver) { t.Fatal("Iteration not over") } @@ -122,7 +122,7 @@ func TestReferenceIterator(t *testing.T) { count++ _, err = iter.Next() } - if !IsErrorCode(err, ErrIterOver) { + if !IsErrorCode(err, ErrorCodeIterOver) { t.Fatal("Iteration not over") } @@ -242,7 +242,7 @@ func TestReferenceNormalizeName(t *testing.T) { } ref, err = ReferenceNormalizeName("foo^", ReferenceFormatNormal) - if !IsErrorCode(err, ErrInvalidSpec) { + if !IsErrorCode(err, ErrorCodeInvalidSpec) { t.Errorf("foo^ should be invalid") } } diff --git a/remote.go b/remote.go index 9d17054..a4b23b5 100644 --- a/remote.go +++ b/remote.go @@ -313,7 +313,7 @@ func certificateCheckCallback(_cert *C.git_cert, _valid C.int, _host *C.char, da C.memcpy(unsafe.Pointer(&cert.Hostkey.HashSHA1[0]), unsafe.Pointer(&ccert.hash_sha1[0]), C.size_t(len(cert.Hostkey.HashSHA1))) } else { cstr := C.CString("Unsupported certificate type") - C.giterr_set_str(C.GITERR_NET, cstr) + C.giterr_set_str(C.int(ErrorClassNet), cstr) C.free(unsafe.Pointer(cstr)) return -1 // we don't support anything else atm } @@ -367,13 +367,12 @@ func freeProxyOptions(ptr *C.git_proxy_options) { C.free(unsafe.Pointer(ptr.url)) } +// RemoteIsValidName returns whether the remote name is well-formed. func RemoteIsValidName(name string) bool { cname := C.CString(name) defer C.free(unsafe.Pointer(cname)) - if C.git_remote_is_valid_name(cname) == 1 { - return true - } - return false + + return C.git_remote_is_valid_name(cname) == 1 } func (r *Remote) Free() { diff --git a/remote_test.go b/remote_test.go index 8b20fd2..7e16856 100644 --- a/remote_test.go +++ b/remote_test.go @@ -27,7 +27,7 @@ func TestListRemotes(t *testing.T) { func assertHostname(cert *Certificate, valid bool, hostname string, t *testing.T) ErrorCode { if hostname != "github.com" { t.Fatal("Hostname does not match") - return ErrUser + return ErrorCodeUser } return 0 diff --git a/reset.go b/reset.go index 031f5bd..b3ecff4 100644 --- a/reset.go +++ b/reset.go @@ -14,7 +14,7 @@ const ( ResetHard ResetType = C.GIT_RESET_HARD ) -func (r *Repository) ResetToCommit(commit *Commit, resetType ResetType, opts *CheckoutOpts) error { +func (r *Repository) ResetToCommit(commit *Commit, resetType ResetType, opts *CheckoutOptions) error { runtime.LockOSThread() defer runtime.UnlockOSThread() ret := C.git_reset(r.ptr, commit.ptr, C.git_reset_t(resetType), opts.toC()) diff --git a/reset_test.go b/reset_test.go index 89ebc49..ff37bfc 100644 --- a/reset_test.go +++ b/reset_test.go @@ -37,7 +37,7 @@ func TestResetToCommit(t *testing.T) { commitToResetTo, err := repo.LookupCommit(commitId) checkFatal(t, err) - repo.ResetToCommit(commitToResetTo, ResetHard, &CheckoutOpts{}) + repo.ResetToCommit(commitToResetTo, ResetHard, &CheckoutOptions{}) // check that the file now reads "testing reset" like it did before bytes, err := ioutil.ReadFile(pathInRepo(repo, "README")) diff --git a/revert.go b/revert.go index e745f11..cabc303 100644 --- a/revert.go +++ b/revert.go @@ -12,7 +12,7 @@ import ( type RevertOptions struct { Mainline uint MergeOpts MergeOptions - CheckoutOpts CheckoutOpts + CheckoutOpts CheckoutOptions } func (opts *RevertOptions) toC() *C.git_revert_options { @@ -33,7 +33,7 @@ func revertOptionsFromC(opts *C.git_revert_options) RevertOptions { } func freeRevertOptions(opts *C.git_revert_options) { - freeCheckoutOpts(&opts.checkout_opts) + freeCheckoutOptions(&opts.checkout_opts) } // DefaultRevertOptions initialises a RevertOptions struct with default values diff --git a/script/build-libgit2.sh b/script/build-libgit2.sh index 8888ec9..c649836 100755 --- a/script/build-libgit2.sh +++ b/script/build-libgit2.sh @@ -61,6 +61,7 @@ cmake -DTHREADSAFE=ON \ -DCMAKE_C_FLAGS=-fPIC \ -DCMAKE_BUILD_TYPE="RelWithDebInfo" \ -DCMAKE_INSTALL_PREFIX="${BUILD_INSTALL_PREFIX}" \ + -DDEPRECATE_HARD=ON \ "${VENDORED_PATH}" && exec cmake --build . --target install diff --git a/stash.go b/stash.go index 8743da8..2b3ea8c 100644 --- a/stash.go +++ b/stash.go @@ -140,7 +140,7 @@ func stashApplyProgressCb(progress C.git_stash_apply_progress_t, handle unsafe.P // StashApplyOptions represents options to control the apply operation. type StashApplyOptions struct { Flags StashApplyFlag - CheckoutOptions CheckoutOpts // options to use when writing files to the working directory + CheckoutOptions CheckoutOptions // options to use when writing files to the working directory ProgressCallback StashApplyProgressCallback // optional callback to notify the consumer of application progress } @@ -173,7 +173,7 @@ func (opts *StashApplyOptions) toC() ( version: C.GIT_STASH_APPLY_OPTIONS_VERSION, flags: C.git_stash_apply_flags(opts.Flags), } - populateCheckoutOpts(&optsC.checkout_options, &opts.CheckoutOptions) + populateCheckoutOptions(&optsC.checkout_options, &opts.CheckoutOptions) if opts.ProgressCallback != nil { C._go_git_setup_stash_apply_progress_callbacks(optsC) optsC.progress_payload = pointerHandles.Track(progressData) @@ -191,21 +191,21 @@ func untrackStashApplyOptionsCallback(optsC *C.git_stash_apply_options) { func freeStashApplyOptions(optsC *C.git_stash_apply_options) { if optsC != nil { - freeCheckoutOpts(&optsC.checkout_options) + freeCheckoutOptions(&optsC.checkout_options) } } // Apply applies a single stashed state from the stash list. // // If local changes in the working directory conflict with changes in the -// stash then ErrConflict will be returned. In this case, the index +// stash then ErrorCodeConflict will be returned. In this case, the index // will always remain unmodified and all files in the working directory will // remain unmodified. However, if you are restoring untracked files or // ignored files and there is a conflict when applying the modified files, // then those files will remain in the working directory. // // If passing the StashApplyReinstateIndex flag and there would be conflicts -// when reinstating the index, the function will return ErrConflict +// when reinstating the index, the function will return ErrorCodeConflict // and both the working directory and index will be left unmodified. // // Note that a minimum checkout strategy of 'CheckoutSafe' is implied. @@ -213,12 +213,12 @@ func freeStashApplyOptions(optsC *C.git_stash_apply_options) { // 'index' is the position within the stash list. 0 points to the most // recent stashed state. // -// Returns error code ErrNotFound if there's no stashed state for the given -// index, error code ErrConflict if local changes in the working directory +// Returns error code ErrorCodeNotFound if there's no stashed state for the given +// index, error code ErrorCodeConflict if local changes in the working directory // conflict with changes in the stash, the user returned error from the // StashApplyProgressCallback, if any, or other error code. // -// Error codes can be interogated with IsErrorCode(err, ErrNotFound). +// Error codes can be interogated with IsErrorCode(err, ErrorCodeNotFound). func (c *StashCollection) Apply(index int, opts StashApplyOptions) error { optsC, progressData := opts.toC() defer untrackStashApplyOptionsCallback(optsC) @@ -298,7 +298,7 @@ func (c *StashCollection) Foreach(callback StashCallback) error { // 'index' is the position within the stash list. 0 points // to the most recent stashed state. // -// Returns error code ErrNotFound if there's no stashed +// Returns error code ErrorCodeNotFound if there's no stashed // state for the given index. func (c *StashCollection) Drop(index int) error { runtime.LockOSThread() @@ -320,7 +320,7 @@ func (c *StashCollection) Drop(index int) error { // // 'opts' controls how stashes are applied. // -// Returns error code ErrNotFound if there's no stashed +// Returns error code ErrorCodeNotFound if there's no stashed // state for the given index. func (c *StashCollection) Pop(index int, opts StashApplyOptions) error { optsC, progressData := opts.toC() diff --git a/stash_test.go b/stash_test.go index 180a16b..62990b1 100644 --- a/stash_test.go +++ b/stash_test.go @@ -56,8 +56,8 @@ func TestStash(t *testing.T) { // Apply: no stash for the given index err = repo.Stashes.Apply(1, opts) - if !IsErrorCode(err, ErrNotFound) { - t.Errorf("expecting GIT_ENOTFOUND error code %d, got %v", ErrNotFound, err) + if !IsErrorCode(err, ErrorCodeNotFound) { + t.Errorf("expecting GIT_ENOTFOUND error code %d, got %v", ErrorCodeNotFound, err) } // Apply: callback stopped diff --git a/submodule.go b/submodule.go index f4b4f15..ea65bfe 100644 --- a/submodule.go +++ b/submodule.go @@ -106,20 +106,21 @@ func (c *SubmoduleCollection) Lookup(name string) (*Submodule, error) { return newSubmoduleFromC(ptr, c.repo), nil } -type SubmoduleCbk func(sub *Submodule, name string) int +// SubmoduleCallback is a function that is called for every submodule found in SubmoduleCollection.Foreach. +type SubmoduleCallback func(sub *Submodule, name string) int -//export SubmoduleVisitor -func SubmoduleVisitor(csub unsafe.Pointer, name *C.char, handle unsafe.Pointer) C.int { +//export submoduleCallback +func submoduleCallback(csub unsafe.Pointer, name *C.char, handle unsafe.Pointer) C.int { sub := &Submodule{(*C.git_submodule)(csub), nil} - if callback, ok := pointerHandles.Get(handle).(SubmoduleCbk); ok { + if callback, ok := pointerHandles.Get(handle).(SubmoduleCallback); ok { return (C.int)(callback(sub, C.GoString(name))) } else { panic("invalid submodule visitor callback") } } -func (c *SubmoduleCollection) Foreach(cbk SubmoduleCbk) error { +func (c *SubmoduleCollection) Foreach(cbk SubmoduleCallback) error { runtime.LockOSThread() defer runtime.UnlockOSThread() @@ -366,7 +367,7 @@ func populateSubmoduleUpdateOptions(ptr *C.git_submodule_update_options, opts *S return nil } - populateCheckoutOpts(&ptr.checkout_opts, opts.CheckoutOpts) + populateCheckoutOptions(&ptr.checkout_opts, opts.CheckoutOpts) populateFetchOptions(&ptr.fetch_opts, opts.FetchOptions) return nil diff --git a/tree.go b/tree.go index b309193..cf85f2e 100644 --- a/tree.go +++ b/tree.go @@ -121,8 +121,8 @@ func (t *Tree) EntryCount() uint64 { type TreeWalkCallback func(string, *TreeEntry) int -//export CallbackGitTreeWalk -func CallbackGitTreeWalk(_root *C.char, entry *C.git_tree_entry, ptr unsafe.Pointer) C.int { +//export treeWalkCallback +func treeWalkCallback(_root *C.char, entry *C.git_tree_entry, ptr unsafe.Pointer) C.int { root := C.GoString(_root) if callback, ok := pointerHandles.Get(ptr).(TreeWalkCallback); ok { diff --git a/walk.go b/walk.go index 287edb6..6020c97 100644 --- a/walk.go +++ b/walk.go @@ -182,7 +182,7 @@ func (v *RevWalk) Iterate(fun RevWalkIterator) (err error) { oid := new(Oid) for { err = v.Next(oid) - if IsErrorCode(err, ErrIterOver) { + if IsErrorCode(err, ErrorCodeIterOver) { return nil } if err != nil { diff --git a/wrapper.c b/wrapper.c index df767fb..7ca2d59 100644 --- a/wrapper.c +++ b/wrapper.c @@ -18,12 +18,12 @@ void _go_git_populate_checkout_cb(git_checkout_options *opts) int _go_git_visit_submodule(git_repository *repo, void *fct) { - return git_submodule_foreach(repo, (gogit_submodule_cbk)&SubmoduleVisitor, fct); + return git_submodule_foreach(repo, (gogit_submodule_cbk)&submoduleCallback, fct); } int _go_git_treewalk(git_tree *tree, git_treewalk_mode mode, void *ptr) { - return git_tree_walk(tree, mode, (git_treewalk_cb)&CallbackGitTreeWalk, ptr); + return git_tree_walk(tree, mode, (git_treewalk_cb)&treeWalkCallback, ptr); } int _go_git_packbuilder_foreach(git_packbuilder *pb, void *payload)