// This is a generated file, modify: generate/templates/templates/class_content.cc

#include <nan.h>
#include <string.h>

extern "C" {
  #include <git2.h>
 }

#include "../include/nodegit.h"
#include "../include/lock_master.h"
#include "../include/functions/copy.h"
#include "../include/note.h"
#include "nodegit_wrapper.cc"

  #include "../include/signature.h"
  #include "../include/oid.h"
  #include "../include/repository.h"
  #include "../include/commit.h"
  #include "../include/note_iterator.h"
  #include "../include/buf.h"
 
#include <iostream>

using namespace std;
using namespace v8;
using namespace node;

  GitNote::~GitNote() {
    // this will cause an error if you have a non-self-freeing object that also needs
    // to save values. Since the object that will eventually free the object has no
    // way of knowing to free these values.
                                                                             }

  void GitNote::InitializeComponent(v8::Local<v8::Object> target, nodegit::Context *nodegitContext) {
    Nan::HandleScope scope;

    v8::Local<v8::External> nodegitExternal = Nan::New<v8::External>(nodegitContext);
    v8::Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(JSNewFunction, nodegitExternal);

    tpl->InstanceTemplate()->SetInternalFieldCount(2);
    tpl->SetClassName(Nan::New("Note").ToLocalChecked());

          Nan::SetPrototypeMethod(tpl, "author", Author, nodegitExternal);
             Nan::SetMethod(tpl, "commitCreate", CommitCreate, nodegitExternal);
             Nan::SetMethod(tpl, "commitIteratorNew", CommitIteratorNew, nodegitExternal);
             Nan::SetMethod(tpl, "commitRead", CommitRead, nodegitExternal);
             Nan::SetMethod(tpl, "commitRemove", CommitRemove, nodegitExternal);
            Nan::SetPrototypeMethod(tpl, "committer", Committer, nodegitExternal);
             Nan::SetMethod(tpl, "create", Create, nodegitExternal);
             Nan::SetMethod(tpl, "defaultRef", DefaultRef, nodegitExternal);
             Nan::SetMethod(tpl, "foreach", Foreach, nodegitExternal);
            Nan::SetPrototypeMethod(tpl, "id", Id, nodegitExternal);
            Nan::SetPrototypeMethod(tpl, "message", Message, nodegitExternal);
             Nan::SetMethod(tpl, "read", Read, nodegitExternal);
             Nan::SetMethod(tpl, "remove", Remove, nodegitExternal);
    
    InitializeTemplate(tpl);

    v8::Local<Function> constructor_template = Nan::GetFunction(tpl).ToLocalChecked();
    nodegitContext->SaveToPersistent("GitNote::Template", constructor_template);
    Nan::Set(target, Nan::New("Note").ToLocalChecked(), constructor_template);
  }

  
/*
     * @return Signature  result    */
NAN_METHOD(GitNote::Author) {
  Nan::EscapableHandleScope scope;


  git_error_clear();

  { // lock master scope start
    nodegit::LockMaster lockMaster(
      /*asyncAction: */false
            ,
              Nan::ObjectWrap::Unwrap<GitNote>(info.This())->GetValue()
    );

 const git_signature * result =     git_note_author(
          Nan::ObjectWrap::Unwrap<GitNote>(info.This())->GetValue()
    );

        // null checks on pointers
        if (!result) {
          return info.GetReturnValue().Set(scope.Escape(Nan::Undefined()));
        }

      v8::Local<v8::Value> v8ConversionSlot;
// start convert_to_v8 block
    if (result != NULL) {
      v8::Local<v8::Array> owners = Nan::New<Array>(0);
            Nan::Set(owners, owners->Length(), info.This());
          v8ConversionSlot = GitSignature::New(
        result,
        true
          , owners
       );
   }
  else {
    v8ConversionSlot = Nan::Null();
  }
  // end convert_to_v8 block
        return info.GetReturnValue().Set(scope.Escape(v8ConversionSlot));
  }
}
   
/*
   * @param Repository repo
   * @param Commit parent
   * @param Signature author
   * @param Signature committer
   * @param Oid oid
   * @param String note
   * @param Number allow_note_overwrite
     * @return Oid notes_commit_out    * @return Oid notes_blob_out    */
NAN_METHOD(GitNote::CommitCreate) {
  Nan::EscapableHandleScope scope;

  if (info.Length() == 0 || !info[0]->IsObject()) {
    return Nan::ThrowError("Repository repo is required.");
  }

  if (info.Length() == 1 || !info[1]->IsObject()) {
    return Nan::ThrowError("Commit parent is required.");
  }

  if (info.Length() == 2 || !info[2]->IsObject()) {
    return Nan::ThrowError("Signature author is required.");
  }

  if (info.Length() == 3 || !info[3]->IsObject()) {
    return Nan::ThrowError("Signature committer is required.");
  }

  if (info.Length() == 4
    || (!info[4]->IsObject() && !info[4]->IsString())) {
    return Nan::ThrowError("Oid oid is required.");
  }
  if (info.Length() == 5 || !info[5]->IsString()) {
    return Nan::ThrowError("String note is required.");
  }

  if (info.Length() == 6 || !info[6]->IsNumber()) {
    return Nan::ThrowError("Number allow_note_overwrite is required.");
  }

      git_oid *notes_commit_out = (git_oid *)malloc(sizeof(git_oid));
      git_oid *notes_blob_out = (git_oid *)malloc(sizeof(git_oid));
// start convert_from_v8 block
  git_repository * from_repo = NULL;
from_repo = Nan::ObjectWrap::Unwrap<GitRepository>(Nan::To<v8::Object>(info[0]).ToLocalChecked())->GetValue();
// end convert_from_v8 block
// start convert_from_v8 block
  git_commit * from_parent = NULL;
from_parent = Nan::ObjectWrap::Unwrap<GitCommit>(Nan::To<v8::Object>(info[1]).ToLocalChecked())->GetValue();
// end convert_from_v8 block
// start convert_from_v8 block
  const git_signature * from_author = NULL;
from_author = Nan::ObjectWrap::Unwrap<GitSignature>(Nan::To<v8::Object>(info[2]).ToLocalChecked())->GetValue();
// end convert_from_v8 block
// start convert_from_v8 block
  const git_signature * from_committer = NULL;
from_committer = Nan::ObjectWrap::Unwrap<GitSignature>(Nan::To<v8::Object>(info[3]).ToLocalChecked())->GetValue();
// end convert_from_v8 block
// start convert_from_v8 block
  const git_oid * from_oid = NULL;
  if (info[4]->IsString()) {
    // Try and parse in a string to a git_oid
    Nan::Utf8String oidString(Nan::To<v8::String>(info[4]).ToLocalChecked());
    git_oid *oidOut = (git_oid *)malloc(sizeof(git_oid));

    if (git_oid_fromstr(oidOut, (const char *) strdup(*oidString)) != GIT_OK) {
      free(oidOut);

      if (git_error_last()->klass != GIT_ERROR_NONE) {
        return Nan::ThrowError(git_error_last()->message);
      } else {
        return Nan::ThrowError("Unknown Error");
      }
    }

    from_oid = oidOut;
  }
  else {
from_oid = Nan::ObjectWrap::Unwrap<GitOid>(Nan::To<v8::Object>(info[4]).ToLocalChecked())->GetValue();
  }
// end convert_from_v8 block
// start convert_from_v8 block
  const char * from_note = NULL;

  Nan::Utf8String note(Nan::To<v8::String>(info[5]).ToLocalChecked());
  // malloc with one extra byte so we can add the terminating null character C-strings expect:
  from_note = (const char *) malloc(note.length() + 1);
  // copy the characters from the nodejs string into our C-string (used instead of strdup or strcpy because nulls in
  // the middle of strings are valid coming from nodejs):
  memcpy((void *)from_note, *note, note.length());
  // ensure the final byte of our new string is null, extra casts added to ensure compatibility with various C types
  // used in the nodejs binding generation:
  memset((void *)(((char *)from_note) + note.length()), 0, 1);
// end convert_from_v8 block
// start convert_from_v8 block
  int from_allow_note_overwrite;
      from_allow_note_overwrite = (int)   info[6].As<v8::Number>()->Value();
// end convert_from_v8 block

  git_error_clear();

  { // lock master scope start
    nodegit::LockMaster lockMaster(
      /*asyncAction: */false
            ,
              from_repo
            ,
              from_parent
            ,
              from_author
            ,
              from_committer
            ,
              from_oid
            ,
              from_note
    );

 int result =     git_note_commit_create(
          notes_commit_out
,          notes_blob_out
,          from_repo
,          from_parent
,          from_author
,          from_committer
,          from_oid
,          from_note
,          from_allow_note_overwrite
    );

      if (info[4]->IsString()) {
        free((void *)from_oid);
      }

      v8::Local<v8::Value> v8ConversionSlot;
        v8::Local<Object> toReturn = Nan::New<Object>();
// start convert_to_v8 block
    if (notes_commit_out != NULL) {
        v8ConversionSlot = GitOid::New(
        notes_commit_out,
        true
       );
   }
  else {
    v8ConversionSlot = Nan::Null();
  }
  // end convert_to_v8 block
          Nan::Set(toReturn, Nan::New("notes_commit_out").ToLocalChecked(), v8ConversionSlot);
// start convert_to_v8 block
    if (notes_blob_out != NULL) {
        v8ConversionSlot = GitOid::New(
        notes_blob_out,
        true
       );
   }
  else {
    v8ConversionSlot = Nan::Null();
  }
  // end convert_to_v8 block
          Nan::Set(toReturn, Nan::New("notes_blob_out").ToLocalChecked(), v8ConversionSlot);
        return info.GetReturnValue().Set(scope.Escape(toReturn));
  }
}
  
/*
  * @param Commit notes_commit
    * @param NoteIterator callback
   */
NAN_METHOD(GitNote::CommitIteratorNew) {

  if (info.Length() == 0 || !info[0]->IsObject()) {
    return Nan::ThrowError("Commit notes_commit is required.");
  }

  if (!info[info.Length() - 1]->IsFunction()) {
    return Nan::ThrowError("Callback is required and must be a Function.");
  }

  CommitIteratorNewBaton* baton = new CommitIteratorNewBaton();

  baton->error_code = GIT_OK;
  baton->error = NULL;


  nodegit::Context *nodegitContext = reinterpret_cast<nodegit::Context *>(info.Data().As<External>()->Value());
  std::map<std::string, std::shared_ptr<nodegit::CleanupHandle>> cleanupHandles;

// start convert_from_v8 block
  git_commit * from_notes_commit = NULL;
from_notes_commit = Nan::ObjectWrap::Unwrap<GitCommit>(Nan::To<v8::Object>(info[0]).ToLocalChecked())->GetValue();
// end convert_from_v8 block
          baton->notes_commit = from_notes_commit;

  Nan::Callback *callback = new Nan::Callback(v8::Local<Function>::Cast(info[info.Length() - 1]));
  CommitIteratorNewWorker *worker = new CommitIteratorNewWorker(baton, callback, cleanupHandles);

             worker->Reference<GitCommit>("notes_commit", info[0]);
  
  nodegitContext->QueueWorker(worker);
  return;
}

nodegit::LockMaster GitNote::CommitIteratorNewWorker::AcquireLocks() {
  nodegit::LockMaster lockMaster(
    /*asyncAction: */true
          ,baton->notes_commit
  );

  return lockMaster;
}

void GitNote::CommitIteratorNewWorker::Execute() {
  git_error_clear();

    int result = git_note_commit_iterator_new(
&baton->out,baton->notes_commit  );

      baton->error_code = result;

      if (result != GIT_OK && git_error_last()->klass != GIT_ERROR_NONE) {
        baton->error = git_error_dup(git_error_last());
      }

}

void GitNote::CommitIteratorNewWorker::HandleErrorCallback() {
  if (!GetIsCancelled()) {
    v8::Local<v8::Object> err = Nan::To<v8::Object>(Nan::Error(ErrorMessage())).ToLocalChecked();
    Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Note.commitIteratorNew").ToLocalChecked());
    v8::Local<v8::Value> argv[1] = {
      err
    };
    callback->Call(1, argv, async_resource);
  }

  if (baton->error) {
    if (baton->error->message) {
      free((void *)baton->error->message);
    }

    free((void *)baton->error);
  }


  delete baton;
}

void GitNote::CommitIteratorNewWorker::HandleOKCallback() {
    if (baton->error_code == GIT_OK) {
    v8::Local<v8::Value> v8ConversionSlot;
// start convert_to_v8 block
    if (baton->out != NULL) {
        v8ConversionSlot = GitNoteIterator::New(
        baton->out,
        false
       );
   }
  else {
    v8ConversionSlot = Nan::Null();
  }
  // end convert_to_v8 block
      v8::Local<v8::Value> result = v8ConversionSlot;
     
    v8::Local<v8::Value> argv[2] = {
      Nan::Null(),
      result
    };
    callback->Call(2, argv, async_resource);
  } else {
    if (baton->error) {
      v8::Local<v8::Object> err;
      if (baton->error->message) {
        err = Nan::To<v8::Object>(Nan::Error(baton->error->message)).ToLocalChecked();
      } else {
        err = Nan::To<v8::Object>(Nan::Error("Method commitIteratorNew has thrown an error.")).ToLocalChecked();
      }
      Nan::Set(err, Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
      Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Note.commitIteratorNew").ToLocalChecked());
      v8::Local<v8::Value> argv[1] = {
        err
      };
      callback->Call(1, argv, async_resource);
      if (baton->error->message)
        free((void *)baton->error->message);
      free((void *)baton->error);
    } else if (baton->error_code < 0) {
      bool callbackFired = false;
      if (!callbackErrorHandle.IsEmpty()) {
        v8::Local<v8::Value> maybeError = Nan::New(callbackErrorHandle);
        if (!maybeError->IsNull() && !maybeError->IsUndefined()) {
          v8::Local<v8::Value> argv[1] = {
            maybeError
          };
          callback->Call(1, argv, async_resource);
          callbackFired = true;
        }
      }

      if (!callbackFired) {
        v8::Local<v8::Object> err = Nan::To<v8::Object>(Nan::Error("Method commitIteratorNew has thrown an error.")).ToLocalChecked();
        Nan::Set(err, Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
        Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Note.commitIteratorNew").ToLocalChecked());
        v8::Local<v8::Value> argv[1] = {
          err
        };
        callback->Call(1, argv, async_resource);
      }
    } else {
      callback->Call(0, NULL, async_resource);
    }

  }


  delete baton;
}

  
/*
  * @param Repository repo
   * @param Commit notes_commit
   * @param Oid oid
    * @param Note callback
   */
NAN_METHOD(GitNote::CommitRead) {

  if (info.Length() == 0 || !info[0]->IsObject()) {
    return Nan::ThrowError("Repository repo is required.");
  }

  if (info.Length() == 1 || !info[1]->IsObject()) {
    return Nan::ThrowError("Commit notes_commit is required.");
  }

  if (info.Length() == 2
    || (!info[2]->IsObject() && !info[2]->IsString())) {
    return Nan::ThrowError("Oid oid is required.");
  }
  if (!info[info.Length() - 1]->IsFunction()) {
    return Nan::ThrowError("Callback is required and must be a Function.");
  }

  CommitReadBaton* baton = new CommitReadBaton();

  baton->error_code = GIT_OK;
  baton->error = NULL;


  nodegit::Context *nodegitContext = reinterpret_cast<nodegit::Context *>(info.Data().As<External>()->Value());
  std::map<std::string, std::shared_ptr<nodegit::CleanupHandle>> cleanupHandles;

// start convert_from_v8 block
  git_repository * from_repo = NULL;
from_repo = Nan::ObjectWrap::Unwrap<GitRepository>(Nan::To<v8::Object>(info[0]).ToLocalChecked())->GetValue();
// end convert_from_v8 block
          baton->repo = from_repo;
// start convert_from_v8 block
  git_commit * from_notes_commit = NULL;
from_notes_commit = Nan::ObjectWrap::Unwrap<GitCommit>(Nan::To<v8::Object>(info[1]).ToLocalChecked())->GetValue();
// end convert_from_v8 block
          baton->notes_commit = from_notes_commit;
// start convert_from_v8 block
  const git_oid * from_oid = NULL;
  if (info[2]->IsString()) {
    // Try and parse in a string to a git_oid
    Nan::Utf8String oidString(Nan::To<v8::String>(info[2]).ToLocalChecked());
    git_oid *oidOut = (git_oid *)malloc(sizeof(git_oid));

    if (git_oid_fromstr(oidOut, (const char *) strdup(*oidString)) != GIT_OK) {
      free(oidOut);

      if (git_error_last()->klass != GIT_ERROR_NONE) {
        return Nan::ThrowError(git_error_last()->message);
      } else {
        return Nan::ThrowError("Unknown Error");
      }
    }

    from_oid = oidOut;
  }
  else {
from_oid = Nan::ObjectWrap::Unwrap<GitOid>(Nan::To<v8::Object>(info[2]).ToLocalChecked())->GetValue();
  }
// end convert_from_v8 block
          baton->oid = from_oid;
            baton->oidNeedsFree = info[2]->IsString();

  Nan::Callback *callback = new Nan::Callback(v8::Local<Function>::Cast(info[info.Length() - 1]));
  CommitReadWorker *worker = new CommitReadWorker(baton, callback, cleanupHandles);

             worker->Reference<GitRepository>("repo", info[0]);
               worker->Reference<GitCommit>("notes_commit", info[1]);
               worker->Reference<GitOid>("oid", info[2]);
  
  nodegitContext->QueueWorker(worker);
  return;
}

nodegit::LockMaster GitNote::CommitReadWorker::AcquireLocks() {
  nodegit::LockMaster lockMaster(
    /*asyncAction: */true
          ,baton->repo
          ,baton->notes_commit
          ,baton->oid
  );

  return lockMaster;
}

void GitNote::CommitReadWorker::Execute() {
  git_error_clear();

    int result = git_note_commit_read(
&baton->out,baton->repo,baton->notes_commit,baton->oid  );

      baton->error_code = result;

      if (result != GIT_OK && git_error_last()->klass != GIT_ERROR_NONE) {
        baton->error = git_error_dup(git_error_last());
      }

}

void GitNote::CommitReadWorker::HandleErrorCallback() {
  if (!GetIsCancelled()) {
    v8::Local<v8::Object> err = Nan::To<v8::Object>(Nan::Error(ErrorMessage())).ToLocalChecked();
    Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Note.commitRead").ToLocalChecked());
    v8::Local<v8::Value> argv[1] = {
      err
    };
    callback->Call(1, argv, async_resource);
  }

  if (baton->error) {
    if (baton->error->message) {
      free((void *)baton->error->message);
    }

    free((void *)baton->error);
  }

      free(baton->out);
      if (baton->oidNeedsFree) {
        baton->oidNeedsFree = false;
        free((void *)baton->oid);
      }

  delete baton;
}

void GitNote::CommitReadWorker::HandleOKCallback() {
    if (baton->error_code == GIT_OK) {
    v8::Local<v8::Value> v8ConversionSlot;
// start convert_to_v8 block
    if (baton->out != NULL) {
        v8ConversionSlot = GitNote::New(
        baton->out,
        true
       );
   }
  else {
    v8ConversionSlot = Nan::Null();
  }
  // end convert_to_v8 block
      v8::Local<v8::Value> result = v8ConversionSlot;
         
    v8::Local<v8::Value> argv[2] = {
      Nan::Null(),
      result
    };
    callback->Call(2, argv, async_resource);
  } else {
    if (baton->error) {
      v8::Local<v8::Object> err;
      if (baton->error->message) {
        err = Nan::To<v8::Object>(Nan::Error(baton->error->message)).ToLocalChecked();
      } else {
        err = Nan::To<v8::Object>(Nan::Error("Method commitRead has thrown an error.")).ToLocalChecked();
      }
      Nan::Set(err, Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
      Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Note.commitRead").ToLocalChecked());
      v8::Local<v8::Value> argv[1] = {
        err
      };
      callback->Call(1, argv, async_resource);
      if (baton->error->message)
        free((void *)baton->error->message);
      free((void *)baton->error);
    } else if (baton->error_code < 0) {
      bool callbackFired = false;
      if (!callbackErrorHandle.IsEmpty()) {
        v8::Local<v8::Value> maybeError = Nan::New(callbackErrorHandle);
        if (!maybeError->IsNull() && !maybeError->IsUndefined()) {
          v8::Local<v8::Value> argv[1] = {
            maybeError
          };
          callback->Call(1, argv, async_resource);
          callbackFired = true;
        }
      }

      if (!callbackFired) {
        v8::Local<v8::Object> err = Nan::To<v8::Object>(Nan::Error("Method commitRead has thrown an error.")).ToLocalChecked();
        Nan::Set(err, Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
        Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Note.commitRead").ToLocalChecked());
        v8::Local<v8::Value> argv[1] = {
          err
        };
        callback->Call(1, argv, async_resource);
      }
    } else {
      callback->Call(0, NULL, async_resource);
    }

        free(baton->out);
  }

      if (baton->oidNeedsFree) {
        baton->oidNeedsFree = false;
        free((void *)baton->oid);
      }

  delete baton;
}

  
/*
  * @param Repository repo
   * @param Commit notes_commit
   * @param Signature author
   * @param Signature committer
   * @param Oid oid
    * @param Oid callback
   */
NAN_METHOD(GitNote::CommitRemove) {

  if (info.Length() == 0 || !info[0]->IsObject()) {
    return Nan::ThrowError("Repository repo is required.");
  }

  if (info.Length() == 1 || !info[1]->IsObject()) {
    return Nan::ThrowError("Commit notes_commit is required.");
  }

  if (info.Length() == 2 || !info[2]->IsObject()) {
    return Nan::ThrowError("Signature author is required.");
  }

  if (info.Length() == 3 || !info[3]->IsObject()) {
    return Nan::ThrowError("Signature committer is required.");
  }

  if (info.Length() == 4
    || (!info[4]->IsObject() && !info[4]->IsString())) {
    return Nan::ThrowError("Oid oid is required.");
  }
  if (!info[info.Length() - 1]->IsFunction()) {
    return Nan::ThrowError("Callback is required and must be a Function.");
  }

  CommitRemoveBaton* baton = new CommitRemoveBaton();

  baton->error_code = GIT_OK;
  baton->error = NULL;


  nodegit::Context *nodegitContext = reinterpret_cast<nodegit::Context *>(info.Data().As<External>()->Value());
  std::map<std::string, std::shared_ptr<nodegit::CleanupHandle>> cleanupHandles;

      baton->notes_commit_out = (git_oid *)malloc(sizeof(git_oid ));
// start convert_from_v8 block
  git_repository * from_repo = NULL;
from_repo = Nan::ObjectWrap::Unwrap<GitRepository>(Nan::To<v8::Object>(info[0]).ToLocalChecked())->GetValue();
// end convert_from_v8 block
          baton->repo = from_repo;
// start convert_from_v8 block
  git_commit * from_notes_commit = NULL;
from_notes_commit = Nan::ObjectWrap::Unwrap<GitCommit>(Nan::To<v8::Object>(info[1]).ToLocalChecked())->GetValue();
// end convert_from_v8 block
          baton->notes_commit = from_notes_commit;
// start convert_from_v8 block
  const git_signature * from_author = NULL;
from_author = Nan::ObjectWrap::Unwrap<GitSignature>(Nan::To<v8::Object>(info[2]).ToLocalChecked())->GetValue();
// end convert_from_v8 block
          baton->author = from_author;
// start convert_from_v8 block
  const git_signature * from_committer = NULL;
from_committer = Nan::ObjectWrap::Unwrap<GitSignature>(Nan::To<v8::Object>(info[3]).ToLocalChecked())->GetValue();
// end convert_from_v8 block
          baton->committer = from_committer;
// start convert_from_v8 block
  const git_oid * from_oid = NULL;
  if (info[4]->IsString()) {
    // Try and parse in a string to a git_oid
    Nan::Utf8String oidString(Nan::To<v8::String>(info[4]).ToLocalChecked());
    git_oid *oidOut = (git_oid *)malloc(sizeof(git_oid));

    if (git_oid_fromstr(oidOut, (const char *) strdup(*oidString)) != GIT_OK) {
      free(oidOut);

      if (git_error_last()->klass != GIT_ERROR_NONE) {
        return Nan::ThrowError(git_error_last()->message);
      } else {
        return Nan::ThrowError("Unknown Error");
      }
    }

    from_oid = oidOut;
  }
  else {
from_oid = Nan::ObjectWrap::Unwrap<GitOid>(Nan::To<v8::Object>(info[4]).ToLocalChecked())->GetValue();
  }
// end convert_from_v8 block
          baton->oid = from_oid;
            baton->oidNeedsFree = info[4]->IsString();

  Nan::Callback *callback = new Nan::Callback(v8::Local<Function>::Cast(info[info.Length() - 1]));
  CommitRemoveWorker *worker = new CommitRemoveWorker(baton, callback, cleanupHandles);

             worker->Reference<GitRepository>("repo", info[0]);
               worker->Reference<GitCommit>("notes_commit", info[1]);
               worker->Reference<GitSignature>("author", info[2]);
               worker->Reference<GitSignature>("committer", info[3]);
               worker->Reference<GitOid>("oid", info[4]);
  
  nodegitContext->QueueWorker(worker);
  return;
}

nodegit::LockMaster GitNote::CommitRemoveWorker::AcquireLocks() {
  nodegit::LockMaster lockMaster(
    /*asyncAction: */true
          ,baton->notes_commit_out
          ,baton->repo
          ,baton->notes_commit
          ,baton->author
          ,baton->committer
          ,baton->oid
  );

  return lockMaster;
}

void GitNote::CommitRemoveWorker::Execute() {
  git_error_clear();

    int result = git_note_commit_remove(
baton->notes_commit_out,baton->repo,baton->notes_commit,baton->author,baton->committer,baton->oid  );

      baton->error_code = result;

      if (result != GIT_OK && git_error_last()->klass != GIT_ERROR_NONE) {
        baton->error = git_error_dup(git_error_last());
      }

}

void GitNote::CommitRemoveWorker::HandleErrorCallback() {
  if (!GetIsCancelled()) {
    v8::Local<v8::Object> err = Nan::To<v8::Object>(Nan::Error(ErrorMessage())).ToLocalChecked();
    Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Note.commitRemove").ToLocalChecked());
    v8::Local<v8::Value> argv[1] = {
      err
    };
    callback->Call(1, argv, async_resource);
  }

  if (baton->error) {
    if (baton->error->message) {
      free((void *)baton->error->message);
    }

    free((void *)baton->error);
  }

      if (baton->oidNeedsFree) {
        baton->oidNeedsFree = false;
        free((void *)baton->oid);
      }

  delete baton;
}

void GitNote::CommitRemoveWorker::HandleOKCallback() {
    if (baton->error_code == GIT_OK) {
    v8::Local<v8::Value> v8ConversionSlot;
// start convert_to_v8 block
    if (baton->notes_commit_out != NULL) {
        v8ConversionSlot = GitOid::New(
        baton->notes_commit_out,
        true
       );
   }
  else {
    v8ConversionSlot = Nan::Null();
  }
  // end convert_to_v8 block
      v8::Local<v8::Value> result = v8ConversionSlot;
             
    v8::Local<v8::Value> argv[2] = {
      Nan::Null(),
      result
    };
    callback->Call(2, argv, async_resource);
  } else {
    if (baton->error) {
      v8::Local<v8::Object> err;
      if (baton->error->message) {
        err = Nan::To<v8::Object>(Nan::Error(baton->error->message)).ToLocalChecked();
      } else {
        err = Nan::To<v8::Object>(Nan::Error("Method commitRemove has thrown an error.")).ToLocalChecked();
      }
      Nan::Set(err, Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
      Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Note.commitRemove").ToLocalChecked());
      v8::Local<v8::Value> argv[1] = {
        err
      };
      callback->Call(1, argv, async_resource);
      if (baton->error->message)
        free((void *)baton->error->message);
      free((void *)baton->error);
    } else if (baton->error_code < 0) {
      bool callbackFired = false;
      if (!callbackErrorHandle.IsEmpty()) {
        v8::Local<v8::Value> maybeError = Nan::New(callbackErrorHandle);
        if (!maybeError->IsNull() && !maybeError->IsUndefined()) {
          v8::Local<v8::Value> argv[1] = {
            maybeError
          };
          callback->Call(1, argv, async_resource);
          callbackFired = true;
        }
      }

      if (!callbackFired) {
        v8::Local<v8::Object> err = Nan::To<v8::Object>(Nan::Error("Method commitRemove has thrown an error.")).ToLocalChecked();
        Nan::Set(err, Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
        Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Note.commitRemove").ToLocalChecked());
        v8::Local<v8::Value> argv[1] = {
          err
        };
        callback->Call(1, argv, async_resource);
      }
    } else {
      callback->Call(0, NULL, async_resource);
    }

  }

      if (baton->oidNeedsFree) {
        baton->oidNeedsFree = false;
        free((void *)baton->oid);
      }

  delete baton;
}

   
/*
     * @return Signature  result    */
NAN_METHOD(GitNote::Committer) {
  Nan::EscapableHandleScope scope;


  git_error_clear();

  { // lock master scope start
    nodegit::LockMaster lockMaster(
      /*asyncAction: */false
            ,
              Nan::ObjectWrap::Unwrap<GitNote>(info.This())->GetValue()
    );

 const git_signature * result =     git_note_committer(
          Nan::ObjectWrap::Unwrap<GitNote>(info.This())->GetValue()
    );

        // null checks on pointers
        if (!result) {
          return info.GetReturnValue().Set(scope.Escape(Nan::Undefined()));
        }

      v8::Local<v8::Value> v8ConversionSlot;
// start convert_to_v8 block
    if (result != NULL) {
        v8ConversionSlot = GitSignature::New(
        result,
        true
       );
   }
  else {
    v8ConversionSlot = Nan::Null();
  }
  // end convert_to_v8 block
        return info.GetReturnValue().Set(scope.Escape(v8ConversionSlot));
  }
}
  
/*
  * @param Repository repo
   * @param String notes_ref
   * @param Signature author
   * @param Signature committer
   * @param Oid oid
   * @param String note
   * @param Number force
    * @param Oid callback
   */
NAN_METHOD(GitNote::Create) {

  if (info.Length() == 0 || !info[0]->IsObject()) {
    return Nan::ThrowError("Repository repo is required.");
  }

  if (info.Length() == 1 || !info[1]->IsString()) {
    return Nan::ThrowError("String notes_ref is required.");
  }

  if (info.Length() == 2 || !info[2]->IsObject()) {
    return Nan::ThrowError("Signature author is required.");
  }

  if (info.Length() == 3 || !info[3]->IsObject()) {
    return Nan::ThrowError("Signature committer is required.");
  }

  if (info.Length() == 4
    || (!info[4]->IsObject() && !info[4]->IsString())) {
    return Nan::ThrowError("Oid oid is required.");
  }
  if (info.Length() == 5 || !info[5]->IsString()) {
    return Nan::ThrowError("String note is required.");
  }

  if (info.Length() == 6 || !info[6]->IsNumber()) {
    return Nan::ThrowError("Number force is required.");
  }

  if (!info[info.Length() - 1]->IsFunction()) {
    return Nan::ThrowError("Callback is required and must be a Function.");
  }

  CreateBaton* baton = new CreateBaton();

  baton->error_code = GIT_OK;
  baton->error = NULL;


  nodegit::Context *nodegitContext = reinterpret_cast<nodegit::Context *>(info.Data().As<External>()->Value());
  std::map<std::string, std::shared_ptr<nodegit::CleanupHandle>> cleanupHandles;

      baton->out = (git_oid *)malloc(sizeof(git_oid ));
// start convert_from_v8 block
  git_repository * from_repo = NULL;
from_repo = Nan::ObjectWrap::Unwrap<GitRepository>(Nan::To<v8::Object>(info[0]).ToLocalChecked())->GetValue();
// end convert_from_v8 block
          baton->repo = from_repo;
// start convert_from_v8 block
  const char * from_notes_ref = NULL;

  Nan::Utf8String notes_ref(Nan::To<v8::String>(info[1]).ToLocalChecked());
  // malloc with one extra byte so we can add the terminating null character C-strings expect:
  from_notes_ref = (const char *) malloc(notes_ref.length() + 1);
  // copy the characters from the nodejs string into our C-string (used instead of strdup or strcpy because nulls in
  // the middle of strings are valid coming from nodejs):
  memcpy((void *)from_notes_ref, *notes_ref, notes_ref.length());
  // ensure the final byte of our new string is null, extra casts added to ensure compatibility with various C types
  // used in the nodejs binding generation:
  memset((void *)(((char *)from_notes_ref) + notes_ref.length()), 0, 1);
// end convert_from_v8 block
          baton->notes_ref = from_notes_ref;
// start convert_from_v8 block
  const git_signature * from_author = NULL;
from_author = Nan::ObjectWrap::Unwrap<GitSignature>(Nan::To<v8::Object>(info[2]).ToLocalChecked())->GetValue();
// end convert_from_v8 block
          baton->author = from_author;
// start convert_from_v8 block
  const git_signature * from_committer = NULL;
from_committer = Nan::ObjectWrap::Unwrap<GitSignature>(Nan::To<v8::Object>(info[3]).ToLocalChecked())->GetValue();
// end convert_from_v8 block
          baton->committer = from_committer;
// start convert_from_v8 block
  const git_oid * from_oid = NULL;
  if (info[4]->IsString()) {
    // Try and parse in a string to a git_oid
    Nan::Utf8String oidString(Nan::To<v8::String>(info[4]).ToLocalChecked());
    git_oid *oidOut = (git_oid *)malloc(sizeof(git_oid));

    if (git_oid_fromstr(oidOut, (const char *) strdup(*oidString)) != GIT_OK) {
      free(oidOut);

      if (git_error_last()->klass != GIT_ERROR_NONE) {
        return Nan::ThrowError(git_error_last()->message);
      } else {
        return Nan::ThrowError("Unknown Error");
      }
    }

    from_oid = oidOut;
  }
  else {
from_oid = Nan::ObjectWrap::Unwrap<GitOid>(Nan::To<v8::Object>(info[4]).ToLocalChecked())->GetValue();
  }
// end convert_from_v8 block
          baton->oid = from_oid;
            baton->oidNeedsFree = info[4]->IsString();
// start convert_from_v8 block
  const char * from_note = NULL;

  Nan::Utf8String note(Nan::To<v8::String>(info[5]).ToLocalChecked());
  // malloc with one extra byte so we can add the terminating null character C-strings expect:
  from_note = (const char *) malloc(note.length() + 1);
  // copy the characters from the nodejs string into our C-string (used instead of strdup or strcpy because nulls in
  // the middle of strings are valid coming from nodejs):
  memcpy((void *)from_note, *note, note.length());
  // ensure the final byte of our new string is null, extra casts added to ensure compatibility with various C types
  // used in the nodejs binding generation:
  memset((void *)(((char *)from_note) + note.length()), 0, 1);
// end convert_from_v8 block
          baton->note = from_note;
// start convert_from_v8 block
  int from_force;
      from_force = (int)   info[6].As<v8::Number>()->Value();
// end convert_from_v8 block
          baton->force = from_force;

  Nan::Callback *callback = new Nan::Callback(v8::Local<Function>::Cast(info[info.Length() - 1]));
  CreateWorker *worker = new CreateWorker(baton, callback, cleanupHandles);

             worker->Reference<GitRepository>("repo", info[0]);
             worker->Reference("notes_ref", info[1]);
              worker->Reference<GitSignature>("author", info[2]);
               worker->Reference<GitSignature>("committer", info[3]);
               worker->Reference<GitOid>("oid", info[4]);
             worker->Reference("note", info[5]);
            worker->Reference("force", info[6]);
 
  nodegitContext->QueueWorker(worker);
  return;
}

nodegit::LockMaster GitNote::CreateWorker::AcquireLocks() {
  nodegit::LockMaster lockMaster(
    /*asyncAction: */true
          ,baton->out
          ,baton->repo
          ,baton->notes_ref
          ,baton->author
          ,baton->committer
          ,baton->oid
          ,baton->note
  );

  return lockMaster;
}

void GitNote::CreateWorker::Execute() {
  git_error_clear();

    int result = git_note_create(
baton->out,baton->repo,baton->notes_ref,baton->author,baton->committer,baton->oid,baton->note,baton->force  );

      baton->error_code = result;

      if (result != GIT_OK && git_error_last()->klass != GIT_ERROR_NONE) {
        baton->error = git_error_dup(git_error_last());
      }

}

void GitNote::CreateWorker::HandleErrorCallback() {
  if (!GetIsCancelled()) {
    v8::Local<v8::Object> err = Nan::To<v8::Object>(Nan::Error(ErrorMessage())).ToLocalChecked();
    Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Note.create").ToLocalChecked());
    v8::Local<v8::Value> argv[1] = {
      err
    };
    callback->Call(1, argv, async_resource);
  }

  if (baton->error) {
    if (baton->error->message) {
      free((void *)baton->error->message);
    }

    free((void *)baton->error);
  }

      if (baton->oidNeedsFree) {
        baton->oidNeedsFree = false;
        free((void *)baton->oid);
      }

  delete baton;
}

void GitNote::CreateWorker::HandleOKCallback() {
    if (baton->error_code == GIT_OK) {
    v8::Local<v8::Value> v8ConversionSlot;
// start convert_to_v8 block
    if (baton->out != NULL) {
        v8ConversionSlot = GitOid::New(
        baton->out,
        true
       );
   }
  else {
    v8ConversionSlot = Nan::Null();
  }
  // end convert_to_v8 block
      v8::Local<v8::Value> result = v8ConversionSlot;
                 
    v8::Local<v8::Value> argv[2] = {
      Nan::Null(),
      result
    };
    callback->Call(2, argv, async_resource);
  } else {
    if (baton->error) {
      v8::Local<v8::Object> err;
      if (baton->error->message) {
        err = Nan::To<v8::Object>(Nan::Error(baton->error->message)).ToLocalChecked();
      } else {
        err = Nan::To<v8::Object>(Nan::Error("Method create has thrown an error.")).ToLocalChecked();
      }
      Nan::Set(err, Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
      Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Note.create").ToLocalChecked());
      v8::Local<v8::Value> argv[1] = {
        err
      };
      callback->Call(1, argv, async_resource);
      if (baton->error->message)
        free((void *)baton->error->message);
      free((void *)baton->error);
    } else if (baton->error_code < 0) {
      bool callbackFired = false;
      if (!callbackErrorHandle.IsEmpty()) {
        v8::Local<v8::Value> maybeError = Nan::New(callbackErrorHandle);
        if (!maybeError->IsNull() && !maybeError->IsUndefined()) {
          v8::Local<v8::Value> argv[1] = {
            maybeError
          };
          callback->Call(1, argv, async_resource);
          callbackFired = true;
        }
      }

      if (!callbackFired) {
        v8::Local<v8::Object> err = Nan::To<v8::Object>(Nan::Error("Method create has thrown an error.")).ToLocalChecked();
        Nan::Set(err, Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
        Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Note.create").ToLocalChecked());
        v8::Local<v8::Value> argv[1] = {
          err
        };
        callback->Call(1, argv, async_resource);
      }
    } else {
      callback->Call(0, NULL, async_resource);
    }

  }

      if (baton->oidNeedsFree) {
        baton->oidNeedsFree = false;
        free((void *)baton->oid);
      }

  delete baton;
}

  
/*
  * @param Repository repo
    * @param Buf callback
   */
NAN_METHOD(GitNote::DefaultRef) {

  if (info.Length() == 0 || !info[0]->IsObject()) {
    return Nan::ThrowError("Repository repo is required.");
  }

  if (!info[info.Length() - 1]->IsFunction()) {
    return Nan::ThrowError("Callback is required and must be a Function.");
  }

  DefaultRefBaton* baton = new DefaultRefBaton();

  baton->error_code = GIT_OK;
  baton->error = NULL;


  nodegit::Context *nodegitContext = reinterpret_cast<nodegit::Context *>(info.Data().As<External>()->Value());
  std::map<std::string, std::shared_ptr<nodegit::CleanupHandle>> cleanupHandles;

// start convert_from_v8 block
  git_repository * from_repo = NULL;
from_repo = Nan::ObjectWrap::Unwrap<GitRepository>(Nan::To<v8::Object>(info[0]).ToLocalChecked())->GetValue();
// end convert_from_v8 block
          baton->repo = from_repo;

  Nan::Callback *callback = new Nan::Callback(v8::Local<Function>::Cast(info[info.Length() - 1]));
  DefaultRefWorker *worker = new DefaultRefWorker(baton, callback, cleanupHandles);

             worker->Reference<GitRepository>("repo", info[0]);
  
  nodegitContext->QueueWorker(worker);
  return;
}

nodegit::LockMaster GitNote::DefaultRefWorker::AcquireLocks() {
  nodegit::LockMaster lockMaster(
    /*asyncAction: */true
          ,baton->out
          ,baton->repo
  );

  return lockMaster;
}

void GitNote::DefaultRefWorker::Execute() {
  git_error_clear();

    int result = git_note_default_ref(
baton->out,baton->repo  );

      baton->error_code = result;

      if (result != GIT_OK && git_error_last()->klass != GIT_ERROR_NONE) {
        baton->error = git_error_dup(git_error_last());
      }

}

void GitNote::DefaultRefWorker::HandleErrorCallback() {
  if (!GetIsCancelled()) {
    v8::Local<v8::Object> err = Nan::To<v8::Object>(Nan::Error(ErrorMessage())).ToLocalChecked();
    Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Note.defaultRef").ToLocalChecked());
    v8::Local<v8::Value> argv[1] = {
      err
    };
    callback->Call(1, argv, async_resource);
  }

  if (baton->error) {
    if (baton->error->message) {
      free((void *)baton->error->message);
    }

    free((void *)baton->error);
  }

        git_buf_dispose(baton->out);
        free((void *)baton->out);

  delete baton;
}

void GitNote::DefaultRefWorker::HandleOKCallback() {
    if (baton->error_code == GIT_OK) {
    v8::Local<v8::Value> v8ConversionSlot;
// start convert_to_v8 block
   if (baton->out) {
    v8ConversionSlot = Nan::New<v8::String>(baton->out->ptr, baton->out->size).ToLocalChecked();
  }
  else {
    v8ConversionSlot = Nan::Null();
  }
  // end convert_to_v8 block
      v8::Local<v8::Value> result = v8ConversionSlot;
     
    v8::Local<v8::Value> argv[2] = {
      Nan::Null(),
      result
    };
    callback->Call(2, argv, async_resource);
  } else {
    if (baton->error) {
      v8::Local<v8::Object> err;
      if (baton->error->message) {
        err = Nan::To<v8::Object>(Nan::Error(baton->error->message)).ToLocalChecked();
      } else {
        err = Nan::To<v8::Object>(Nan::Error("Method defaultRef has thrown an error.")).ToLocalChecked();
      }
      Nan::Set(err, Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
      Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Note.defaultRef").ToLocalChecked());
      v8::Local<v8::Value> argv[1] = {
        err
      };
      callback->Call(1, argv, async_resource);
      if (baton->error->message)
        free((void *)baton->error->message);
      free((void *)baton->error);
    } else if (baton->error_code < 0) {
      bool callbackFired = false;
      if (!callbackErrorHandle.IsEmpty()) {
        v8::Local<v8::Value> maybeError = Nan::New(callbackErrorHandle);
        if (!maybeError->IsNull() && !maybeError->IsUndefined()) {
          v8::Local<v8::Value> argv[1] = {
            maybeError
          };
          callback->Call(1, argv, async_resource);
          callbackFired = true;
        }
      }

      if (!callbackFired) {
        v8::Local<v8::Object> err = Nan::To<v8::Object>(Nan::Error("Method defaultRef has thrown an error.")).ToLocalChecked();
        Nan::Set(err, Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
        Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Note.defaultRef").ToLocalChecked());
        v8::Local<v8::Value> argv[1] = {
          err
        };
        callback->Call(1, argv, async_resource);
      }
    } else {
      callback->Call(0, NULL, async_resource);
    }

  }

        git_buf_dispose(baton->out);
        free((void *)baton->out);

  delete baton;
}

  
/*
 * @param Repository repo
   * @param String notes_ref
   * @param NoteForeachCb note_cb
   * @param Void payload
     */
NAN_METHOD(GitNote::Foreach) {

  if (info.Length() == 0 || !info[0]->IsObject()) {
    return Nan::ThrowError("Repository repo is required.");
  }

  if (info.Length() == 1 || !info[1]->IsString()) {
    return Nan::ThrowError("String notes_ref is required.");
  }

  if (info.Length() == 2 || !info[2]->IsFunction()) {
    return Nan::ThrowError("NoteForeachCb note_cb is required.");
  }
  if (!info[info.Length() - 1]->IsFunction()) {
    return Nan::ThrowError("Callback is required and must be a Function.");
  }

  ForeachBaton* baton = new ForeachBaton();

  baton->error_code = GIT_OK;
  baton->error = NULL;

      Foreach_globalPayload* globalPayload = new Foreach_globalPayload;

  nodegit::Context *nodegitContext = reinterpret_cast<nodegit::Context *>(info.Data().As<External>()->Value());
  std::map<std::string, std::shared_ptr<nodegit::CleanupHandle>> cleanupHandles;

// start convert_from_v8 block
  git_repository * from_repo = NULL;
from_repo = Nan::ObjectWrap::Unwrap<GitRepository>(Nan::To<v8::Object>(info[0]).ToLocalChecked())->GetValue();
// end convert_from_v8 block
          baton->repo = from_repo;
// start convert_from_v8 block
  const char * from_notes_ref = NULL;

  Nan::Utf8String notes_ref(Nan::To<v8::String>(info[1]).ToLocalChecked());
  // malloc with one extra byte so we can add the terminating null character C-strings expect:
  from_notes_ref = (const char *) malloc(notes_ref.length() + 1);
  // copy the characters from the nodejs string into our C-string (used instead of strdup or strcpy because nulls in
  // the middle of strings are valid coming from nodejs):
  memcpy((void *)from_notes_ref, *notes_ref, notes_ref.length());
  // ensure the final byte of our new string is null, extra casts added to ensure compatibility with various C types
  // used in the nodejs binding generation:
  memset((void *)(((char *)from_notes_ref) + notes_ref.length()), 0, 1);
// end convert_from_v8 block
          baton->notes_ref = from_notes_ref;
        if (!info[2]->IsFunction()) {
          baton->note_cb = NULL;
          globalPayload->note_cb = NULL;
        }
        else {
          baton->note_cb = Foreach_note_cb_cppCallback;
            globalPayload->note_cb = new Nan::Callback(info[2].As<Function>());
        }
          baton->payload = globalPayload;

  Nan::Callback *callback = new Nan::Callback(v8::Local<Function>::Cast(info[info.Length() - 1]));
  ForeachWorker *worker = new ForeachWorker(baton, callback, cleanupHandles);

             worker->Reference<GitRepository>("repo", info[0]);
             worker->Reference("notes_ref", info[1]);
            worker->Reference("payload", info[3]);
 
  nodegitContext->QueueWorker(worker);
  return;
}

nodegit::LockMaster GitNote::ForeachWorker::AcquireLocks() {
  nodegit::LockMaster lockMaster(
    /*asyncAction: */true
          ,baton->repo
          ,baton->notes_ref
          ,baton->payload
  );

  return lockMaster;
}

void GitNote::ForeachWorker::Execute() {
  git_error_clear();

    int result = git_note_foreach(
baton->repo,baton->notes_ref,baton->note_cb,baton->payload  );

      baton->error_code = result;

      if (result != GIT_OK && git_error_last()->klass != GIT_ERROR_NONE) {
        baton->error = git_error_dup(git_error_last());
      }

}

void GitNote::ForeachWorker::HandleErrorCallback() {
  if (!GetIsCancelled()) {
    v8::Local<v8::Object> err = Nan::To<v8::Object>(Nan::Error(ErrorMessage())).ToLocalChecked();
    Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Note.foreach").ToLocalChecked());
    v8::Local<v8::Value> argv[1] = {
      err
    };
    callback->Call(1, argv, async_resource);
  }

  if (baton->error) {
    if (baton->error->message) {
      free((void *)baton->error->message);
    }

    free((void *)baton->error);
  }

      delete (Foreach_globalPayload*)baton->payload;

  delete baton;
}

void GitNote::ForeachWorker::HandleOKCallback() {
    if (baton->error_code == GIT_OK) {
    v8::Local<v8::Value> result = Nan::Undefined();
         
    v8::Local<v8::Value> argv[2] = {
      Nan::Null(),
      result
    };
    callback->Call(2, argv, async_resource);
  } else {
    if (baton->error) {
      v8::Local<v8::Object> err;
      if (baton->error->message) {
        err = Nan::To<v8::Object>(Nan::Error(baton->error->message)).ToLocalChecked();
      } else {
        err = Nan::To<v8::Object>(Nan::Error("Method foreach has thrown an error.")).ToLocalChecked();
      }
      Nan::Set(err, Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
      Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Note.foreach").ToLocalChecked());
      v8::Local<v8::Value> argv[1] = {
        err
      };
      callback->Call(1, argv, async_resource);
      if (baton->error->message)
        free((void *)baton->error->message);
      free((void *)baton->error);
    } else if (baton->error_code < 0) {
      bool callbackFired = false;
      if (!callbackErrorHandle.IsEmpty()) {
        v8::Local<v8::Value> maybeError = Nan::New(callbackErrorHandle);
        if (!maybeError->IsNull() && !maybeError->IsUndefined()) {
          v8::Local<v8::Value> argv[1] = {
            maybeError
          };
          callback->Call(1, argv, async_resource);
          callbackFired = true;
        }
      }

      if (!callbackFired) {
        v8::Local<v8::Object> err = Nan::To<v8::Object>(Nan::Error("Method foreach has thrown an error.")).ToLocalChecked();
        Nan::Set(err, Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
        Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Note.foreach").ToLocalChecked());
        v8::Local<v8::Value> argv[1] = {
          err
        };
        callback->Call(1, argv, async_resource);
      }
    } else {
      callback->Call(0, NULL, async_resource);
    }

  }

      delete (Foreach_globalPayload*)baton->payload;

  delete baton;
}


int GitNote::Foreach_note_cb_cppCallback (
    const git_oid * blob_id,     const git_oid * annotated_object_id,     void * payload  ) {
  Foreach_NoteCbBaton baton(0);

    baton.blob_id = blob_id;
    baton.annotated_object_id = annotated_object_id;
    baton.payload = payload;
 
  return baton.ExecuteAsync(Foreach_note_cb_async, Foreach_note_cb_cancelAsync);
}

void GitNote::Foreach_note_cb_cancelAsync(void *untypedBaton) {
  Foreach_NoteCbBaton* baton = static_cast<Foreach_NoteCbBaton*>(untypedBaton);
  baton->result = -1;
  baton->Done();
}

void GitNote::Foreach_note_cb_async(void *untypedBaton) {
  Nan::HandleScope scope;

  Foreach_NoteCbBaton* baton = static_cast<Foreach_NoteCbBaton*>(untypedBaton);

    Nan::Callback* callback = ((Foreach_globalPayload*)baton->payload)->note_cb;
   
  v8::Local<v8::Value> argv[2] = {
         GitOid::New(baton->blob_id, false)
 ,          GitOid::New(baton->annotated_object_id, false)
    };

  Nan::TryCatch tryCatch;
  Nan::MaybeLocal<v8::Value> maybeResult = (*callback)(baton->GetAsyncResource(), 2, argv);

  v8::Local<v8::Value> result;
  if (!maybeResult.IsEmpty()) {
    result = maybeResult.ToLocalChecked();
  }

  if(PromiseCompletion::ForwardIfPromise(result, baton, Foreach_note_cb_promiseCompleted)) {
    return;
  }

    if (result.IsEmpty() || result->IsNativeError()) {
      baton->result = -1;
    }
    else if (!result->IsNull() && !result->IsUndefined()) {
       if (result->IsNumber()) {
        baton->result = Nan::To<int>(result).FromJust();
      }
      else {
        baton->result = baton->defaultResult;
      }
     }
    else {
      baton->result = baton->defaultResult;
    }
 
  baton->Done();
}

void GitNote::Foreach_note_cb_promiseCompleted(bool isFulfilled, nodegit::AsyncBaton *_baton, v8::Local<v8::Value> result) {
  Nan::HandleScope scope;

  Foreach_NoteCbBaton* baton = static_cast<Foreach_NoteCbBaton*>(_baton);

  if (isFulfilled) {
      if (result.IsEmpty() || result->IsNativeError()) {
        baton->result = -1;
      }
      else if (!result->IsNull() && !result->IsUndefined()) {
         if (result->IsNumber()) {
          baton->result = Nan::To<int>(result).FromJust();
        }
        else {
          baton->result = baton->defaultResult;
        }
       }
      else {
        baton->result = baton->defaultResult;
      }
   }
  else {
    // promise was rejected
    GitNote* instance = static_cast<GitNote*>(baton->  payload  );
    v8::Local<v8::Object> parent = instance->handle();
    SetPrivate(parent, Nan::New("NodeGitPromiseError").ToLocalChecked(), result);

    baton->result = -1;
  }
  baton->Done();
}
   
/*
     * @return Oid  result    */
NAN_METHOD(GitNote::Id) {
  Nan::EscapableHandleScope scope;


  git_error_clear();

  { // lock master scope start
    nodegit::LockMaster lockMaster(
      /*asyncAction: */false
            ,
              Nan::ObjectWrap::Unwrap<GitNote>(info.This())->GetValue()
    );

 const git_oid * result =     git_note_id(
          Nan::ObjectWrap::Unwrap<GitNote>(info.This())->GetValue()
    );

        // null checks on pointers
        if (!result) {
          return info.GetReturnValue().Set(scope.Escape(Nan::Undefined()));
        }

      v8::Local<v8::Value> v8ConversionSlot;
// start convert_to_v8 block
    if (result != NULL) {
      v8::Local<v8::Array> owners = Nan::New<Array>(0);
            Nan::Set(owners, owners->Length(), info.This());
          v8ConversionSlot = GitOid::New(
        result,
        true
          , owners
       );
   }
  else {
    v8ConversionSlot = Nan::Null();
  }
  // end convert_to_v8 block
        return info.GetReturnValue().Set(scope.Escape(v8ConversionSlot));
  }
}
   
/*
     * @return String  result    */
NAN_METHOD(GitNote::Message) {
  Nan::EscapableHandleScope scope;


  git_error_clear();

  { // lock master scope start
    nodegit::LockMaster lockMaster(
      /*asyncAction: */false
            ,
              Nan::ObjectWrap::Unwrap<GitNote>(info.This())->GetValue()
    );

 const char * result =     git_note_message(
          Nan::ObjectWrap::Unwrap<GitNote>(info.This())->GetValue()
    );

        // null checks on pointers
        if (!result) {
          return info.GetReturnValue().Set(scope.Escape(Nan::Undefined()));
        }

      v8::Local<v8::Value> v8ConversionSlot;
// start convert_to_v8 block
  if (result){
       v8ConversionSlot = Nan::New<v8::String>(result).ToLocalChecked();
   }
  else {
    v8ConversionSlot = Nan::Null();
  }

  // end convert_to_v8 block
        return info.GetReturnValue().Set(scope.Escape(v8ConversionSlot));
  }
}
  
/*
  * @param Repository repo
   * @param String notes_ref
   * @param Oid oid
    * @param Note callback
   */
NAN_METHOD(GitNote::Read) {

  if (info.Length() == 0 || !info[0]->IsObject()) {
    return Nan::ThrowError("Repository repo is required.");
  }

  if (info.Length() == 1 || !info[1]->IsString()) {
    return Nan::ThrowError("String notes_ref is required.");
  }

  if (info.Length() == 2
    || (!info[2]->IsObject() && !info[2]->IsString())) {
    return Nan::ThrowError("Oid oid is required.");
  }
  if (!info[info.Length() - 1]->IsFunction()) {
    return Nan::ThrowError("Callback is required and must be a Function.");
  }

  ReadBaton* baton = new ReadBaton();

  baton->error_code = GIT_OK;
  baton->error = NULL;


  nodegit::Context *nodegitContext = reinterpret_cast<nodegit::Context *>(info.Data().As<External>()->Value());
  std::map<std::string, std::shared_ptr<nodegit::CleanupHandle>> cleanupHandles;

// start convert_from_v8 block
  git_repository * from_repo = NULL;
from_repo = Nan::ObjectWrap::Unwrap<GitRepository>(Nan::To<v8::Object>(info[0]).ToLocalChecked())->GetValue();
// end convert_from_v8 block
          baton->repo = from_repo;
// start convert_from_v8 block
  const char * from_notes_ref = NULL;

  Nan::Utf8String notes_ref(Nan::To<v8::String>(info[1]).ToLocalChecked());
  // malloc with one extra byte so we can add the terminating null character C-strings expect:
  from_notes_ref = (const char *) malloc(notes_ref.length() + 1);
  // copy the characters from the nodejs string into our C-string (used instead of strdup or strcpy because nulls in
  // the middle of strings are valid coming from nodejs):
  memcpy((void *)from_notes_ref, *notes_ref, notes_ref.length());
  // ensure the final byte of our new string is null, extra casts added to ensure compatibility with various C types
  // used in the nodejs binding generation:
  memset((void *)(((char *)from_notes_ref) + notes_ref.length()), 0, 1);
// end convert_from_v8 block
          baton->notes_ref = from_notes_ref;
// start convert_from_v8 block
  const git_oid * from_oid = NULL;
  if (info[2]->IsString()) {
    // Try and parse in a string to a git_oid
    Nan::Utf8String oidString(Nan::To<v8::String>(info[2]).ToLocalChecked());
    git_oid *oidOut = (git_oid *)malloc(sizeof(git_oid));

    if (git_oid_fromstr(oidOut, (const char *) strdup(*oidString)) != GIT_OK) {
      free(oidOut);

      if (git_error_last()->klass != GIT_ERROR_NONE) {
        return Nan::ThrowError(git_error_last()->message);
      } else {
        return Nan::ThrowError("Unknown Error");
      }
    }

    from_oid = oidOut;
  }
  else {
from_oid = Nan::ObjectWrap::Unwrap<GitOid>(Nan::To<v8::Object>(info[2]).ToLocalChecked())->GetValue();
  }
// end convert_from_v8 block
          baton->oid = from_oid;
            baton->oidNeedsFree = info[2]->IsString();

  Nan::Callback *callback = new Nan::Callback(v8::Local<Function>::Cast(info[info.Length() - 1]));
  ReadWorker *worker = new ReadWorker(baton, callback, cleanupHandles);

             worker->Reference<GitRepository>("repo", info[0]);
             worker->Reference("notes_ref", info[1]);
              worker->Reference<GitOid>("oid", info[2]);
  
  nodegitContext->QueueWorker(worker);
  return;
}

nodegit::LockMaster GitNote::ReadWorker::AcquireLocks() {
  nodegit::LockMaster lockMaster(
    /*asyncAction: */true
          ,baton->repo
          ,baton->notes_ref
          ,baton->oid
  );

  return lockMaster;
}

void GitNote::ReadWorker::Execute() {
  git_error_clear();

    int result = git_note_read(
&baton->out,baton->repo,baton->notes_ref,baton->oid  );

      baton->error_code = result;

      if (result != GIT_OK && git_error_last()->klass != GIT_ERROR_NONE) {
        baton->error = git_error_dup(git_error_last());
      }

}

void GitNote::ReadWorker::HandleErrorCallback() {
  if (!GetIsCancelled()) {
    v8::Local<v8::Object> err = Nan::To<v8::Object>(Nan::Error(ErrorMessage())).ToLocalChecked();
    Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Note.read").ToLocalChecked());
    v8::Local<v8::Value> argv[1] = {
      err
    };
    callback->Call(1, argv, async_resource);
  }

  if (baton->error) {
    if (baton->error->message) {
      free((void *)baton->error->message);
    }

    free((void *)baton->error);
  }

      git_note_free(baton->out);
      if (baton->oidNeedsFree) {
        baton->oidNeedsFree = false;
        free((void *)baton->oid);
      }

  delete baton;
}

void GitNote::ReadWorker::HandleOKCallback() {
    if (baton->error_code == GIT_OK) {
    v8::Local<v8::Value> v8ConversionSlot;
// start convert_to_v8 block
    if (baton->out != NULL) {
        v8ConversionSlot = GitNote::New(
        baton->out,
        true
       );
   }
  else {
    v8ConversionSlot = Nan::Null();
  }
  // end convert_to_v8 block
      v8::Local<v8::Value> result = v8ConversionSlot;
         
    v8::Local<v8::Value> argv[2] = {
      Nan::Null(),
      result
    };
    callback->Call(2, argv, async_resource);
  } else {
    if (baton->error) {
      v8::Local<v8::Object> err;
      if (baton->error->message) {
        err = Nan::To<v8::Object>(Nan::Error(baton->error->message)).ToLocalChecked();
      } else {
        err = Nan::To<v8::Object>(Nan::Error("Method read has thrown an error.")).ToLocalChecked();
      }
      Nan::Set(err, Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
      Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Note.read").ToLocalChecked());
      v8::Local<v8::Value> argv[1] = {
        err
      };
      callback->Call(1, argv, async_resource);
      if (baton->error->message)
        free((void *)baton->error->message);
      free((void *)baton->error);
    } else if (baton->error_code < 0) {
      bool callbackFired = false;
      if (!callbackErrorHandle.IsEmpty()) {
        v8::Local<v8::Value> maybeError = Nan::New(callbackErrorHandle);
        if (!maybeError->IsNull() && !maybeError->IsUndefined()) {
          v8::Local<v8::Value> argv[1] = {
            maybeError
          };
          callback->Call(1, argv, async_resource);
          callbackFired = true;
        }
      }

      if (!callbackFired) {
        v8::Local<v8::Object> err = Nan::To<v8::Object>(Nan::Error("Method read has thrown an error.")).ToLocalChecked();
        Nan::Set(err, Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
        Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Note.read").ToLocalChecked());
        v8::Local<v8::Value> argv[1] = {
          err
        };
        callback->Call(1, argv, async_resource);
      }
    } else {
      callback->Call(0, NULL, async_resource);
    }

        git_note_free(baton->out);
  }

      if (baton->oidNeedsFree) {
        baton->oidNeedsFree = false;
        free((void *)baton->oid);
      }

  delete baton;
}

  
/*
 * @param Repository repo
   * @param String notes_ref
   * @param Signature author
   * @param Signature committer
   * @param Oid oid
     */
NAN_METHOD(GitNote::Remove) {

  if (info.Length() == 0 || !info[0]->IsObject()) {
    return Nan::ThrowError("Repository repo is required.");
  }

  if (info.Length() == 1 || !info[1]->IsString()) {
    return Nan::ThrowError("String notes_ref is required.");
  }

  if (info.Length() == 2 || !info[2]->IsObject()) {
    return Nan::ThrowError("Signature author is required.");
  }

  if (info.Length() == 3 || !info[3]->IsObject()) {
    return Nan::ThrowError("Signature committer is required.");
  }

  if (info.Length() == 4
    || (!info[4]->IsObject() && !info[4]->IsString())) {
    return Nan::ThrowError("Oid oid is required.");
  }
  if (!info[info.Length() - 1]->IsFunction()) {
    return Nan::ThrowError("Callback is required and must be a Function.");
  }

  RemoveBaton* baton = new RemoveBaton();

  baton->error_code = GIT_OK;
  baton->error = NULL;


  nodegit::Context *nodegitContext = reinterpret_cast<nodegit::Context *>(info.Data().As<External>()->Value());
  std::map<std::string, std::shared_ptr<nodegit::CleanupHandle>> cleanupHandles;

// start convert_from_v8 block
  git_repository * from_repo = NULL;
from_repo = Nan::ObjectWrap::Unwrap<GitRepository>(Nan::To<v8::Object>(info[0]).ToLocalChecked())->GetValue();
// end convert_from_v8 block
          baton->repo = from_repo;
// start convert_from_v8 block
  const char * from_notes_ref = NULL;

  Nan::Utf8String notes_ref(Nan::To<v8::String>(info[1]).ToLocalChecked());
  // malloc with one extra byte so we can add the terminating null character C-strings expect:
  from_notes_ref = (const char *) malloc(notes_ref.length() + 1);
  // copy the characters from the nodejs string into our C-string (used instead of strdup or strcpy because nulls in
  // the middle of strings are valid coming from nodejs):
  memcpy((void *)from_notes_ref, *notes_ref, notes_ref.length());
  // ensure the final byte of our new string is null, extra casts added to ensure compatibility with various C types
  // used in the nodejs binding generation:
  memset((void *)(((char *)from_notes_ref) + notes_ref.length()), 0, 1);
// end convert_from_v8 block
          baton->notes_ref = from_notes_ref;
// start convert_from_v8 block
  const git_signature * from_author = NULL;
from_author = Nan::ObjectWrap::Unwrap<GitSignature>(Nan::To<v8::Object>(info[2]).ToLocalChecked())->GetValue();
// end convert_from_v8 block
          baton->author = from_author;
// start convert_from_v8 block
  const git_signature * from_committer = NULL;
from_committer = Nan::ObjectWrap::Unwrap<GitSignature>(Nan::To<v8::Object>(info[3]).ToLocalChecked())->GetValue();
// end convert_from_v8 block
          baton->committer = from_committer;
// start convert_from_v8 block
  const git_oid * from_oid = NULL;
  if (info[4]->IsString()) {
    // Try and parse in a string to a git_oid
    Nan::Utf8String oidString(Nan::To<v8::String>(info[4]).ToLocalChecked());
    git_oid *oidOut = (git_oid *)malloc(sizeof(git_oid));

    if (git_oid_fromstr(oidOut, (const char *) strdup(*oidString)) != GIT_OK) {
      free(oidOut);

      if (git_error_last()->klass != GIT_ERROR_NONE) {
        return Nan::ThrowError(git_error_last()->message);
      } else {
        return Nan::ThrowError("Unknown Error");
      }
    }

    from_oid = oidOut;
  }
  else {
from_oid = Nan::ObjectWrap::Unwrap<GitOid>(Nan::To<v8::Object>(info[4]).ToLocalChecked())->GetValue();
  }
// end convert_from_v8 block
          baton->oid = from_oid;
            baton->oidNeedsFree = info[4]->IsString();

  Nan::Callback *callback = new Nan::Callback(v8::Local<Function>::Cast(info[info.Length() - 1]));
  RemoveWorker *worker = new RemoveWorker(baton, callback, cleanupHandles);

             worker->Reference<GitRepository>("repo", info[0]);
             worker->Reference("notes_ref", info[1]);
              worker->Reference<GitSignature>("author", info[2]);
               worker->Reference<GitSignature>("committer", info[3]);
               worker->Reference<GitOid>("oid", info[4]);
  
  nodegitContext->QueueWorker(worker);
  return;
}

nodegit::LockMaster GitNote::RemoveWorker::AcquireLocks() {
  nodegit::LockMaster lockMaster(
    /*asyncAction: */true
          ,baton->repo
          ,baton->notes_ref
          ,baton->author
          ,baton->committer
          ,baton->oid
  );

  return lockMaster;
}

void GitNote::RemoveWorker::Execute() {
  git_error_clear();

    int result = git_note_remove(
baton->repo,baton->notes_ref,baton->author,baton->committer,baton->oid  );

      baton->error_code = result;

      if (result != GIT_OK && git_error_last()->klass != GIT_ERROR_NONE) {
        baton->error = git_error_dup(git_error_last());
      }

}

void GitNote::RemoveWorker::HandleErrorCallback() {
  if (!GetIsCancelled()) {
    v8::Local<v8::Object> err = Nan::To<v8::Object>(Nan::Error(ErrorMessage())).ToLocalChecked();
    Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Note.remove").ToLocalChecked());
    v8::Local<v8::Value> argv[1] = {
      err
    };
    callback->Call(1, argv, async_resource);
  }

  if (baton->error) {
    if (baton->error->message) {
      free((void *)baton->error->message);
    }

    free((void *)baton->error);
  }

      if (baton->oidNeedsFree) {
        baton->oidNeedsFree = false;
        free((void *)baton->oid);
      }

  delete baton;
}

void GitNote::RemoveWorker::HandleOKCallback() {
    if (baton->error_code == GIT_OK) {
    v8::Local<v8::Value> result = Nan::Undefined();
           
    v8::Local<v8::Value> argv[2] = {
      Nan::Null(),
      result
    };
    callback->Call(2, argv, async_resource);
  } else {
    if (baton->error) {
      v8::Local<v8::Object> err;
      if (baton->error->message) {
        err = Nan::To<v8::Object>(Nan::Error(baton->error->message)).ToLocalChecked();
      } else {
        err = Nan::To<v8::Object>(Nan::Error("Method remove has thrown an error.")).ToLocalChecked();
      }
      Nan::Set(err, Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
      Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Note.remove").ToLocalChecked());
      v8::Local<v8::Value> argv[1] = {
        err
      };
      callback->Call(1, argv, async_resource);
      if (baton->error->message)
        free((void *)baton->error->message);
      free((void *)baton->error);
    } else if (baton->error_code < 0) {
      bool callbackFired = false;
      if (!callbackErrorHandle.IsEmpty()) {
        v8::Local<v8::Value> maybeError = Nan::New(callbackErrorHandle);
        if (!maybeError->IsNull() && !maybeError->IsUndefined()) {
          v8::Local<v8::Value> argv[1] = {
            maybeError
          };
          callback->Call(1, argv, async_resource);
          callbackFired = true;
        }
      }

      if (!callbackFired) {
        v8::Local<v8::Object> err = Nan::To<v8::Object>(Nan::Error("Method remove has thrown an error.")).ToLocalChecked();
        Nan::Set(err, Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
        Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("Note.remove").ToLocalChecked());
        v8::Local<v8::Value> argv[1] = {
          err
        };
        callback->Call(1, argv, async_resource);
      }
    } else {
      callback->Call(0, NULL, async_resource);
    }

  }

      if (baton->oidNeedsFree) {
        baton->oidNeedsFree = false;
        free((void *)baton->oid);
      }

  delete baton;
}

    // force base class template instantiation, to make sure we get all the
// methods, statics, etc.
template class NodeGitWrapper<GitNoteTraits>;
 