refactor!: use Finalizer to automatically free allocated memory for objects (#48)

BREAKING CHANGE: signature change for remote and repository callbacks during repository clone operation.
This commit is contained in:
Aleksey Kulikov 2022-04-28 11:04:48 +03:00 committed by GitHub
parent 94c40f9a94
commit a3213a88a2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
103 changed files with 2278 additions and 2595 deletions

View file

@ -14,20 +14,17 @@ class AnnotatedCommit {
/// It is preferable to use [AnnotatedCommit.fromReference] instead of this
/// one, for commit to contain more information about how it was looked up.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
AnnotatedCommit.lookup({required Repository repo, required Oid oid}) {
_annotatedCommitPointer = bindings.lookup(
repoPointer: repo.pointer,
oidPointer: oid.pointer,
);
_finalizer.attach(this, _annotatedCommitPointer, detach: this);
}
/// Creates an annotated commit from the given [reference].
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
AnnotatedCommit.fromReference({
required Repository repo,
@ -37,6 +34,7 @@ class AnnotatedCommit {
repoPointer: repo.pointer,
referencePointer: reference.pointer,
);
_finalizer.attach(this, _annotatedCommitPointer, detach: this);
}
/// Creates an annotated commit from a revision string.
@ -44,8 +42,6 @@ class AnnotatedCommit {
/// See `man gitrevisions`, or http://git-scm.com/docs/git-rev-parse.html#_specifying_revisions
/// for information on the syntax accepted.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
AnnotatedCommit.fromRevSpec({
required Repository repo,
@ -55,6 +51,7 @@ class AnnotatedCommit {
repoPointer: repo.pointer,
revspec: spec,
);
_finalizer.attach(this, _annotatedCommitPointer, detach: this);
}
/// Creates an annotated commit from the given fetch head data.
@ -67,8 +64,6 @@ class AnnotatedCommit {
///
/// [oid] is the commit object id of the remote branch.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
AnnotatedCommit.fromFetchHead({
required Repository repo,
@ -82,6 +77,7 @@ class AnnotatedCommit {
remoteUrl: remoteUrl,
oid: oid.pointer,
);
_finalizer.attach(this, _annotatedCommitPointer, detach: this);
}
late final Pointer<git_annotated_commit> _annotatedCommitPointer;
@ -98,5 +94,14 @@ class AnnotatedCommit {
String get refName => bindings.refName(_annotatedCommitPointer);
/// Releases memory allocated for commit object.
void free() => bindings.free(_annotatedCommitPointer);
void free() {
bindings.free(_annotatedCommitPointer);
_finalizer.detach(this);
}
}
// coverage:ignore-start
final _finalizer = Finalizer<Pointer<git_annotated_commit>>(
(pointer) => bindings.free(pointer),
);
// coverage:ignore-end

View file

@ -27,11 +27,14 @@ Pointer<git_annotated_commit> lookup({
oidPointer,
);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -49,11 +52,14 @@ Pointer<git_annotated_commit> fromRef({
referencePointer,
);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -75,13 +81,15 @@ Pointer<git_annotated_commit> fromRevSpec({
revspecC,
);
final result = out.value;
calloc.free(revspecC);
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -105,14 +113,16 @@ Pointer<git_annotated_commit> fromFetchHead({
oid,
);
final result = out.value;
calloc.free(out);
calloc.free(branchNameC);
calloc.free(remoteUrlC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}

View file

@ -19,27 +19,25 @@ Object? getAttribute({
final nameC = name.toNativeUtf8().cast<Int8>();
libgit2.git_attr_get(out, repoPointer, flags, pathC, nameC);
final result = out.value;
calloc.free(out);
calloc.free(pathC);
calloc.free(nameC);
final attributeValue = libgit2.git_attr_value(out.value);
final attributeValue = libgit2.git_attr_value(result);
if (attributeValue == git_attr_value_t.GIT_ATTR_VALUE_UNSPECIFIED) {
calloc.free(out);
return null;
}
if (attributeValue == git_attr_value_t.GIT_ATTR_VALUE_TRUE) {
calloc.free(out);
return true;
}
if (attributeValue == git_attr_value_t.GIT_ATTR_VALUE_FALSE) {
calloc.free(out);
return false;
}
if (attributeValue == git_attr_value_t.GIT_ATTR_VALUE_STRING) {
final result = out.value.cast<Utf8>().toDartString();
calloc.free(out);
return result;
return result.cast<Utf8>().toDartString();
}
return null;
}

View file

@ -47,14 +47,16 @@ Pointer<git_blame> file({
final error = libgit2.git_blame_file(out, repoPointer, pathC, options);
final result = out.value;
calloc.free(out);
calloc.free(pathC);
calloc.free(options);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -80,13 +82,15 @@ Pointer<git_blame> buffer({
buffer.length,
);
final result = out.value;
calloc.free(out);
calloc.free(bufferC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}

View file

@ -16,11 +16,14 @@ Pointer<git_blob> lookup({
final out = calloc<Pointer<git_blob>>();
final error = libgit2.git_blob_lookup(out, repoPointer, oidPointer);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -128,7 +131,11 @@ Pointer<git_oid> createFromDisk({
Pointer<git_blob> duplicate(Pointer<git_blob> source) {
final out = calloc<Pointer<git_blob>>();
libgit2.git_blob_dup(out, source);
return out.value;
final result = out.value;
calloc.free(out);
return result;
}
/// Get a buffer with the filtered content of a blob.
@ -156,15 +163,19 @@ String filterContent({
final error = libgit2.git_blob_filter(out, blobPointer, asPathC, opts);
late final String result;
if (out.ref.ptr != nullptr) {
result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
}
libgit2.git_buf_dispose(out);
calloc.free(out);
calloc.free(asPathC);
calloc.free(opts);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
calloc.free(out);
return result;
}
}

View file

@ -35,13 +35,15 @@ List<Pointer<git_reference>> list({
error = libgit2.git_branch_next(reference, refType, iterator.value);
if (error == 0) {
result.add(reference.value);
calloc.free(refType);
} else {
break;
}
calloc.free(reference);
calloc.free(refType);
}
libgit2.git_branch_iterator_free(iterator.value);
calloc.free(iterator);
return result;
}
@ -65,13 +67,15 @@ Pointer<git_reference> lookup({
branchType,
);
final result = out.value;
calloc.free(out);
calloc.free(branchNameC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -103,13 +107,15 @@ Pointer<git_reference> create({
forceC,
);
final result = out.value;
calloc.free(out);
calloc.free(branchNameC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -192,13 +198,14 @@ String name(Pointer<git_reference> ref) {
final out = calloc<Pointer<Int8>>();
final error = libgit2.git_branch_name(out, ref);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
final result = out.value.cast<Utf8>().toDartString();
calloc.free(out);
return result;
return result.cast<Utf8>().toDartString();
}
}
@ -218,14 +225,15 @@ String remoteName({
final branchNameC = branchName.toNativeUtf8().cast<Int8>();
final error = libgit2.git_branch_remote_name(out, repoPointer, branchNameC);
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
libgit2.git_buf_dispose(out);
calloc.free(out);
calloc.free(branchNameC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
calloc.free(out);
return result;
}
}
@ -240,11 +248,14 @@ Pointer<git_reference> getUpstream(Pointer<git_reference> branch) {
final out = calloc<Pointer<git_reference>>();
final error = libgit2.git_branch_upstream(out, branch);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -286,14 +297,15 @@ String upstreamName({
final branchNameC = branchName.toNativeUtf8().cast<Int8>();
final error = libgit2.git_branch_upstream_name(out, repoPointer, branchNameC);
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
libgit2.git_buf_dispose(out);
calloc.free(out);
calloc.free(branchNameC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
calloc.free(out);
return result;
}
}
@ -316,14 +328,15 @@ String upstreamRemote({
branchNameC,
);
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
libgit2.git_buf_dispose(out);
calloc.free(out);
calloc.free(branchNameC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
calloc.free(out);
return result;
}
}
@ -346,12 +359,15 @@ String upstreamMerge({
branchNameC,
);
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
libgit2.git_buf_dispose(out);
calloc.free(out);
calloc.free(branchNameC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
calloc.free(out);
return result;
}
}

View file

@ -17,11 +17,14 @@ Pointer<git_commit> lookup({
final out = calloc<Pointer<git_commit>>();
final error = libgit2.git_commit_lookup(out, repoPointer, oidPointer);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -124,17 +127,18 @@ String createBuffer({
parentsC,
);
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
libgit2.git_buf_dispose(out);
calloc.free(out);
calloc.free(updateRefC);
calloc.free(messageEncodingC);
calloc.free(messageC);
calloc.free(parentsC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
calloc.free(out);
return result;
}
}
@ -196,7 +200,12 @@ Pointer<git_oid> amend({
Pointer<git_commit> duplicate(Pointer<git_commit> source) {
final out = calloc<Pointer<git_commit>>();
libgit2.git_commit_dup(out, source);
return out.value;
final result = out.value;
calloc.free(out);
return result;
}
/// Get the encoding for the message of a commit, as a string representing a
@ -254,14 +263,15 @@ String headerField({
final fieldC = field.toNativeUtf8().cast<Int8>();
final error = libgit2.git_commit_header_field(out, commitPointer, fieldC);
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
libgit2.git_buf_dispose(out);
calloc.free(out);
calloc.free(fieldC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
calloc.free(out);
return result;
}
}
@ -292,11 +302,14 @@ Pointer<git_commit> parent({
final out = calloc<Pointer<git_commit>>();
final error = libgit2.git_commit_parent(out, commitPointer, position);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -315,11 +328,14 @@ Pointer<git_commit> nthGenAncestor({
final out = calloc<Pointer<git_commit>>();
final error = libgit2.git_commit_nth_gen_ancestor(out, commitPointer, n);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -350,7 +366,12 @@ Pointer<git_oid> treeOid(Pointer<git_commit> commit) {
Pointer<git_tree> tree(Pointer<git_commit> commit) {
final out = calloc<Pointer<git_tree>>();
libgit2.git_commit_tree(out, commit);
return out.value;
final result = out.value;
calloc.free(out);
return result;
}
/// Reverts the given commit, producing changes in the index and working
@ -393,13 +414,15 @@ Pointer<git_index> revertCommit({
opts,
);
final result = out.value;
calloc.free(out);
calloc.free(opts);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}

View file

@ -29,11 +29,14 @@ Pointer<git_config> openDefault() {
final out = calloc<Pointer<git_config>>();
final error = libgit2.git_config_open_default(out);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -54,12 +57,14 @@ String findGlobal() {
final out = calloc<git_buf>();
final error = libgit2.git_config_find_global(out);
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
libgit2.git_buf_dispose(out);
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
calloc.free(out);
return result;
}
}
@ -73,12 +78,14 @@ String findSystem() {
final out = calloc<git_buf>();
final error = libgit2.git_config_find_system(out);
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
libgit2.git_buf_dispose(out);
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
calloc.free(out);
return result;
}
}
@ -93,12 +100,14 @@ String findXdg() {
final out = calloc<git_buf>();
final error = libgit2.git_config_find_xdg(out);
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
libgit2.git_buf_dispose(out);
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
calloc.free(out);
return result;
}
}
@ -111,7 +120,12 @@ String findXdg() {
Pointer<git_config> snapshot(Pointer<git_config> config) {
final out = calloc<Pointer<git_config>>();
libgit2.git_config_snapshot(out, config);
return out.value;
final result = out.value;
calloc.free(out);
return result;
}
/// Get the config entry of a config variable.
@ -122,16 +136,18 @@ Pointer<git_config_entry> getEntry({
required String variable,
}) {
final out = calloc<Pointer<git_config_entry>>();
final name = variable.toNativeUtf8().cast<Int8>();
final error = libgit2.git_config_get_entry(out, configPointer, name);
final nameC = variable.toNativeUtf8().cast<Int8>();
final error = libgit2.git_config_get_entry(out, configPointer, nameC);
calloc.free(name);
final result = out.value;
calloc.free(out);
calloc.free(nameC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -142,10 +158,10 @@ void setBool({
required String variable,
required bool value,
}) {
final name = variable.toNativeUtf8().cast<Int8>();
final nameC = variable.toNativeUtf8().cast<Int8>();
final valueC = value ? 1 : 0;
libgit2.git_config_set_bool(configPointer, name, valueC);
calloc.free(name);
libgit2.git_config_set_bool(configPointer, nameC, valueC);
calloc.free(nameC);
}
/// Set the value of an integer config variable in the config file with the
@ -155,9 +171,9 @@ void setInt({
required String variable,
required int value,
}) {
final name = variable.toNativeUtf8().cast<Int8>();
libgit2.git_config_set_int64(configPointer, name, value);
calloc.free(name);
final nameC = variable.toNativeUtf8().cast<Int8>();
libgit2.git_config_set_int64(configPointer, nameC, value);
calloc.free(nameC);
}
/// Set the value of a string config variable in the config file with the
@ -167,10 +183,10 @@ void setString({
required String variable,
required String value,
}) {
final name = variable.toNativeUtf8().cast<Int8>();
final nameC = variable.toNativeUtf8().cast<Int8>();
final valueC = value.toNativeUtf8().cast<Int8>();
libgit2.git_config_set_string(configPointer, name, valueC);
calloc.free(name);
libgit2.git_config_set_string(configPointer, nameC, valueC);
calloc.free(nameC);
calloc.free(valueC);
}
@ -178,7 +194,12 @@ void setString({
Pointer<git_config_iterator> iterator(Pointer<git_config> cfg) {
final out = calloc<Pointer<git_config_iterator>>();
libgit2.git_config_iterator_new(out, cfg);
return out.value;
final result = out.value;
calloc.free(out);
return result;
}
/// Delete a config variable from the config file with the highest level
@ -189,10 +210,10 @@ void delete({
required Pointer<git_config> configPointer,
required String variable,
}) {
final name = variable.toNativeUtf8().cast<Int8>();
final error = libgit2.git_config_delete_entry(configPointer, name);
final nameC = variable.toNativeUtf8().cast<Int8>();
final error = libgit2.git_config_delete_entry(configPointer, nameC);
calloc.free(name);
calloc.free(nameC);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
@ -208,7 +229,7 @@ List<String> multivarValues({
required String variable,
String? regexp,
}) {
final name = variable.toNativeUtf8().cast<Int8>();
final nameC = variable.toNativeUtf8().cast<Int8>();
final regexpC = regexp?.toNativeUtf8().cast<Int8>() ?? nullptr;
final iterator = calloc<Pointer<git_config_iterator>>();
final entry = calloc<Pointer<git_config_entry>>();
@ -216,7 +237,7 @@ List<String> multivarValues({
libgit2.git_config_multivar_iterator_new(
iterator,
configPointer,
name,
nameC,
regexpC,
);
@ -232,8 +253,9 @@ List<String> multivarValues({
}
}
calloc.free(name);
calloc.free(nameC);
calloc.free(regexpC);
libgit2.git_config_iterator_free(iterator.value);
calloc.free(iterator);
calloc.free(entry);
@ -250,13 +272,13 @@ void setMultivar({
required String regexp,
required String value,
}) {
final name = variable.toNativeUtf8().cast<Int8>();
final nameC = variable.toNativeUtf8().cast<Int8>();
final regexpC = regexp.toNativeUtf8().cast<Int8>();
final valueC = value.toNativeUtf8().cast<Int8>();
libgit2.git_config_set_multivar(configPointer, name, regexpC, valueC);
libgit2.git_config_set_multivar(configPointer, nameC, regexpC, valueC);
calloc.free(name);
calloc.free(nameC);
calloc.free(regexpC);
calloc.free(valueC);
}
@ -270,14 +292,22 @@ void deleteMultivar({
required String variable,
required String regexp,
}) {
final name = variable.toNativeUtf8().cast<Int8>();
final nameC = variable.toNativeUtf8().cast<Int8>();
final regexpC = regexp.toNativeUtf8().cast<Int8>();
libgit2.git_config_delete_multivar(configPointer, name, regexpC);
libgit2.git_config_delete_multivar(configPointer, nameC, regexpC);
calloc.free(name);
calloc.free(nameC);
calloc.free(regexpC);
}
/// Free the configuration and its associated memory and files.
void free(Pointer<git_config> cfg) => libgit2.git_config_free(cfg);
/// Free a config entry.
void freeEntry(Pointer<git_config_entry> entry) =>
libgit2.git_config_entry_free(entry);
/// Free a config iterator.
void freeIterator(Pointer<git_config_iterator> iter) =>
libgit2.git_config_iterator_free(iter);

View file

@ -15,10 +15,13 @@ Pointer<git_credential> userPass({
libgit2.git_credential_userpass_plaintext_new(out, usernameC, passwordC);
final result = out.value;
calloc.free(out);
calloc.free(usernameC);
calloc.free(passwordC);
return out.value;
return result;
}
/// Create a new passphrase-protected ssh key credential object.
@ -42,12 +45,15 @@ Pointer<git_credential> sshKey({
passPhraseC,
);
final result = out.value;
calloc.free(out);
calloc.free(usernameC);
calloc.free(publicKeyC);
calloc.free(privateKeyC);
calloc.free(passPhraseC);
return out.value;
return result;
}
/// Create a new ssh key credential object used for querying an ssh-agent.
@ -57,9 +63,12 @@ Pointer<git_credential> sshKeyFromAgent(String username) {
libgit2.git_credential_ssh_key_from_agent(out, usernameC);
final result = out.value;
calloc.free(out);
calloc.free(usernameC);
return out.value;
return result;
}
/// Create a new ssh key credential object reading the keys from memory.
@ -83,10 +92,13 @@ Pointer<git_credential> sshKeyFromMemory({
passPhraseC,
);
final result = out.value;
calloc.free(out);
calloc.free(usernameC);
calloc.free(publicKeyC);
calloc.free(privateKeyC);
calloc.free(passPhraseC);
return out.value;
return result;
}

View file

@ -32,13 +32,15 @@ Pointer<git_describe_result> commit({
final error = libgit2.git_describe_commit(out, commitPointer.cast(), opts);
final result = out.value;
calloc.free(out);
calloc.free(opts);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -68,13 +70,15 @@ Pointer<git_describe_result> workdir({
final error = libgit2.git_describe_workdir(out, repo, opts);
final result = out.value;
calloc.free(out);
calloc.free(opts);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -106,8 +110,9 @@ String format({
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
calloc.free(opts);
libgit2.git_buf_dispose(out);
calloc.free(out);
calloc.free(opts);
return result;
}

View file

@ -31,13 +31,15 @@ Pointer<git_diff> indexToIndex({
opts,
);
final result = out.value;
calloc.free(out);
calloc.free(opts);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -58,9 +60,12 @@ Pointer<git_diff> indexToWorkdir({
libgit2.git_diff_index_to_workdir(out, repoPointer, indexPointer, opts);
final result = out.value;
calloc.free(out);
calloc.free(opts);
return out.value;
return result;
}
/// Create a diff between a tree and repository index.
@ -87,9 +92,12 @@ Pointer<git_diff> treeToIndex({
opts,
);
final result = out.value;
calloc.free(out);
calloc.free(opts);
return out.value;
return result;
}
/// Create a diff between a tree and the working directory.
@ -116,13 +124,15 @@ Pointer<git_diff> treeToWorkdir({
opts,
);
final result = out.value;
calloc.free(out);
calloc.free(opts);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -155,13 +165,15 @@ Pointer<git_diff> treeToWorkdirWithIndex({
opts,
);
final result = out.value;
calloc.free(out);
calloc.free(opts);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -191,13 +203,15 @@ Pointer<git_diff> treeToTree({
opts,
);
final result = out.value;
calloc.free(out);
calloc.free(opts);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -235,9 +249,12 @@ Pointer<git_diff> parse(String content) {
final contentC = content.toNativeUtf8().cast<Int8>();
libgit2.git_diff_from_buffer(out, contentC, content.length);
final result = out.value;
calloc.free(out);
calloc.free(contentC);
return out.value;
return result;
}
/// Transform a diff marking file renames, copies, etc.
@ -324,11 +341,14 @@ Pointer<git_diff_stats> stats(Pointer<git_diff> diff) {
final out = calloc<Pointer<git_diff_stats>>();
final error = libgit2.git_diff_get_stats(out, diff);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -355,12 +375,14 @@ String statsPrint({
final out = calloc<git_buf>();
final error = libgit2.git_diff_stats_to_buf(out, statsPointer, format, width);
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
libgit2.git_buf_dispose(out);
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
calloc.free(out);
return result;
}
}
@ -369,10 +391,14 @@ String statsPrint({
String addToBuf(Pointer<git_diff> diff) {
final out = calloc<git_buf>();
libgit2.git_diff_to_buf(out, diff, git_diff_format_t.GIT_DIFF_FORMAT_PATCH);
final result = out.ref.ptr == nullptr
? ''
: out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
libgit2.git_buf_dispose(out);
calloc.free(out);
return result;
}
@ -462,14 +488,16 @@ Pointer<git_index> applyToTree({
opts,
);
final result = out.value;
calloc.free(out);
calloc.free(payload);
calloc.free(opts);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}

View file

@ -14,7 +14,12 @@ import 'package:libgit2dart/src/util.dart';
Pointer<git_index> newInMemory() {
final out = calloc<Pointer<git_index>>();
libgit2.git_index_new(out);
return out.value;
final result = out.value;
calloc.free(out);
return result;
}
/// Read index capabilities flags.
@ -266,6 +271,8 @@ void addFromBuffer({
buffer.length,
);
calloc.free(bufferC);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
@ -452,12 +459,12 @@ List<Map<String, Pointer<git_index_entry>>> conflictList(
'our': ourOut.value,
'their': theirOut.value,
});
calloc.free(ancestorOut);
calloc.free(ourOut);
calloc.free(theirOut);
} else {
break;
}
calloc.free(ancestorOut);
calloc.free(ourOut);
calloc.free(theirOut);
}
libgit2.git_index_conflict_iterator_free(iterator.value);

View file

@ -13,7 +13,11 @@ Pointer<git_mailmap> init() {
final out = calloc<Pointer<git_mailmap>>();
libgit2.git_mailmap_new(out);
return out.value;
final result = out.value;
calloc.free(out);
return result;
}
/// Create a new mailmap instance containing a single mailmap file.
@ -23,9 +27,12 @@ Pointer<git_mailmap> fromBuffer(String buffer) {
libgit2.git_mailmap_from_buffer(out, bufferC, buffer.length);
final result = out.value;
calloc.free(out);
calloc.free(bufferC);
return out.value;
return result;
}
/// Create a new mailmap instance from a repository, loading mailmap files based
@ -43,11 +50,14 @@ Pointer<git_mailmap> fromRepository(Pointer<git_repository> repo) {
final out = calloc<Pointer<git_mailmap>>();
final error = libgit2.git_mailmap_from_repository(out, repo);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -87,7 +97,11 @@ Pointer<git_signature> resolveSignature({
final out = calloc<Pointer<git_signature>>();
libgit2.git_mailmap_resolve_signature(out, mailmapPointer, signaturePointer);
return out.value;
final result = out.value;
calloc.free(out);
return result;
}
/// Add a single entry to the given mailmap object. If the entry already exists,

View file

@ -234,12 +234,16 @@ String mergeFileFromIndex({
nullptr,
);
late final String result;
if (out.ref.ptr != nullptr) {
result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.len);
}
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.len);
calloc.free(out);
return result;
}
}
@ -275,13 +279,15 @@ Pointer<git_index> mergeCommits({
opts,
);
final result = out.value;
calloc.free(out);
calloc.free(opts);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -318,13 +324,15 @@ Pointer<git_index> mergeTrees({
opts,
);
final result = out.value;
calloc.free(out);
calloc.free(opts);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}

View file

@ -30,15 +30,21 @@ List<Map<String, Pointer>> list(Pointer<git_repository> repo) {
if (nextError >= 0) {
final out = calloc<Pointer<git_note>>();
libgit2.git_note_read(out, repo, notesRef, annotatedOid);
calloc.free(noteOid);
result.add({'note': out.value, 'annotatedOid': annotatedOid});
final note = out.value;
calloc.free(out);
result.add({'note': note, 'annotatedOid': annotatedOid});
} else {
break;
}
calloc.free(noteOid);
}
calloc.free(notesRef);
libgit2.git_note_iterator_free(iterator.value);
calloc.free(iterator);
return result;
}
@ -57,13 +63,15 @@ Pointer<git_note> lookup({
final notesRefC = notesRef.toNativeUtf8().cast<Int8>();
final error = libgit2.git_note_read(out, repoPointer, notesRefC, oidPointer);
final result = out.value;
calloc.free(out);
calloc.free(notesRefC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}

View file

@ -26,11 +26,14 @@ Pointer<git_object> lookup({
final out = calloc<Pointer<git_object>>();
final error = libgit2.git_object_lookup(out, repoPointer, oidPointer, type);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}

View file

@ -14,7 +14,12 @@ import 'package:libgit2dart/src/util.dart';
Pointer<git_odb> create() {
final out = calloc<Pointer<git_odb>>();
libgit2.git_odb_new(out);
return out.value;
final result = out.value;
calloc.free(out);
return result;
}
/// Add an on-disk alternate to an existing Object DB.
@ -78,8 +83,7 @@ int _forEachCb(
Pointer<git_oid> oid,
Pointer<Void> payload,
) {
final _oid = oid_bindings.copy(oid);
_objects.add(Oid(_oid));
_objects.add(Oid(oid_bindings.copy(oid)));
return 0;
}
@ -121,11 +125,14 @@ Pointer<git_odb_object> read({
final out = calloc<Pointer<git_odb_object>>();
final error = libgit2.git_odb_read(out, odbPointer, oidPointer);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -186,14 +193,15 @@ Pointer<git_oid> write({
throw LibGit2Error(libgit2.git_error_last());
}
final buffer = data.toNativeUtf8().cast<Int8>();
libgit2.git_odb_stream_write(stream.value, buffer, data.length);
final bufferC = data.toNativeUtf8().cast<Int8>();
libgit2.git_odb_stream_write(stream.value, bufferC, data.length);
final out = calloc<git_oid>();
libgit2.git_odb_stream_finalize_write(out, stream.value);
calloc.free(buffer);
calloc.free(bufferC);
libgit2.git_odb_stream_free(stream.value);
calloc.free(stream);
return out;
}

View file

@ -7,10 +7,10 @@ import 'package:libgit2dart/src/util.dart';
/// Parse N characters of a hex formatted object id into a git_oid.
Pointer<git_oid> fromStrN(String hex) {
final out = calloc<git_oid>();
final str = hex.toNativeUtf8().cast<Int8>();
libgit2.git_oid_fromstrn(out, str, hex.length);
final hexC = hex.toNativeUtf8().cast<Int8>();
libgit2.git_oid_fromstrn(out, hexC, hex.length);
calloc.free(str);
calloc.free(hexC);
return out;
}
@ -18,10 +18,10 @@ Pointer<git_oid> fromStrN(String hex) {
/// Parse a hex formatted object id into a git_oid.
Pointer<git_oid> fromSHA(String hex) {
final out = calloc<git_oid>();
final str = hex.toNativeUtf8().cast<Int8>();
libgit2.git_oid_fromstr(out, str);
final hexC = hex.toNativeUtf8().cast<Int8>();
libgit2.git_oid_fromstr(out, hexC);
calloc.free(str);
calloc.free(hexC);
return out;
}

View file

@ -12,11 +12,14 @@ Pointer<git_packbuilder> init(Pointer<git_repository> repo) {
final out = calloc<Pointer<git_packbuilder>>();
final error = libgit2.git_packbuilder_new(out, repo);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}

View file

@ -42,14 +42,17 @@ Pointer<git_patch> fromBuffers({
opts,
);
final result = out.value;
calloc.free(out);
calloc.free(oldAsPathC);
calloc.free(newAsPathC);
calloc.free(opts);
// We are not freeing buffers because patch object does not have reference to
// underlying buffers. So if the buffer is freed the patch text becomes
// corrupted.
// We are not freeing buffers `oldBufferC` and `newBufferC` because patch
// object does not have reference to underlying buffers. So if the buffer is
// freed the patch text becomes corrupted.
return out.value;
return result;
}
/// Directly generate a patch from the difference between two blobs.
@ -83,11 +86,14 @@ Pointer<git_patch> fromBlobs({
opts,
);
final result = out.value;
calloc.free(out);
calloc.free(oldAsPathC);
calloc.free(newAsPathC);
calloc.free(opts);
return out.value;
return result;
}
/// Directly generate a patch from the difference between a blob and a buffer.
@ -124,11 +130,17 @@ Pointer<git_patch> fromBlobAndBuffer({
opts,
);
final result = out.value;
calloc.free(out);
calloc.free(oldAsPathC);
calloc.free(bufferAsPathC);
calloc.free(opts);
// We are not freeing buffer `bufferC` because patch object does not have
// reference to underlying buffers. So if the buffer is freed the patch text
// becomes corrupted.
return out.value;
return result;
}
/// Return a patch for an entry in the diff list.
@ -145,11 +157,14 @@ Pointer<git_patch> fromDiff({
final out = calloc<Pointer<git_patch>>();
final error = libgit2.git_patch_from_diff(out, diffPointer, index);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -172,9 +187,13 @@ Map<String, Object> hunk({
final linesInHunk = calloc<Int64>();
libgit2.git_patch_get_hunk(out, linesInHunk.cast(), patchPointer, hunkIndex);
final hunk = out.value;
final linesN = linesInHunk.value;
calloc.free(out);
calloc.free(linesInHunk);
return {'hunk': out.value, 'linesN': linesN};
return {'hunk': hunk, 'linesN': linesN};
}
/// Get line counts of each type in a patch.
@ -211,7 +230,11 @@ Pointer<git_diff_line> lines({
final out = calloc<Pointer<git_diff_line>>();
libgit2.git_patch_get_line_in_hunk(out, patchPointer, hunkIndex, lineOfHunk);
return out.value;
final result = out.value;
calloc.free(out);
return result;
}
/// Get the content of a patch as a single diff text.
@ -221,12 +244,14 @@ String text(Pointer<git_patch> patch) {
final out = calloc<git_buf>();
final error = libgit2.git_patch_to_buf(out, patch);
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
libgit2.git_buf_dispose(out);
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
calloc.free(out);
return result;
}
}

View file

@ -40,13 +40,15 @@ Pointer<git_rebase> init({
opts,
);
final result = out.value;
calloc.free(out);
calloc.free(opts);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -61,11 +63,14 @@ Pointer<git_rebase> open(Pointer<git_repository> repo) {
final error = libgit2.git_rebase_open(out, repo, opts);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -100,11 +105,14 @@ Pointer<git_rebase_operation> next(Pointer<git_rebase> rebase) {
final out = calloc<Pointer<git_rebase_operation>>();
final error = libgit2.git_rebase_next(out, rebase);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}

View file

@ -33,11 +33,14 @@ Pointer<git_reference> resolve(Pointer<git_reference> ref) {
final out = calloc<Pointer<git_reference>>();
final error = libgit2.git_reference_resolve(out, ref);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -56,13 +59,15 @@ Pointer<git_reference> lookup({
final nameC = name.toNativeUtf8().cast<Int8>();
final error = libgit2.git_reference_lookup(out, repoPointer, nameC);
final result = out.value;
calloc.free(out);
calloc.free(nameC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -110,14 +115,16 @@ Pointer<git_reference> rename({
logMessageC,
);
final result = out.value;
calloc.free(out);
calloc.free(newNameC);
calloc.free(logMessageC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -149,10 +156,10 @@ bool hasLog({
required Pointer<git_repository> repoPointer,
required String name,
}) {
final refname = name.toNativeUtf8().cast<Int8>();
final result = libgit2.git_reference_has_log(repoPointer, refname);
final nameC = name.toNativeUtf8().cast<Int8>();
final result = libgit2.git_reference_has_log(repoPointer, nameC);
calloc.free(refname);
calloc.free(nameC);
return result == 1 || false;
}
@ -244,14 +251,16 @@ Pointer<git_reference> createDirect({
logMessageC,
);
final result = out.value;
calloc.free(out);
calloc.free(nameC);
calloc.free(logMessageC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -303,15 +312,17 @@ Pointer<git_reference> createSymbolic({
logMessageC,
);
final result = out.value;
calloc.free(out);
calloc.free(nameC);
calloc.free(targetC);
calloc.free(logMessageC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -348,13 +359,15 @@ Pointer<git_reference> setTarget({
logMessageC,
);
final result = out.value;
calloc.free(out);
calloc.free(logMessageC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -386,14 +399,16 @@ Pointer<git_reference> setTargetSymbolic({
logMessageC,
);
final result = out.value;
calloc.free(out);
calloc.free(targetC);
calloc.free(logMessageC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -421,11 +436,14 @@ Pointer<git_object> peel({
final out = calloc<Pointer<git_object>>();
final error = libgit2.git_reference_peel(out, refPointer, type);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -433,7 +451,12 @@ Pointer<git_object> peel({
Pointer<git_reference> duplicate(Pointer<git_reference> source) {
final out = calloc<Pointer<git_reference>>();
libgit2.git_reference_dup(out, source);
return out.value;
final result = out.value;
calloc.free(out);
return result;
}
/// Free the given reference.

View file

@ -19,9 +19,12 @@ Pointer<git_reflog> read({
final nameC = name.toNativeUtf8().cast<Int8>();
libgit2.git_reflog_read(out, repoPointer, nameC);
final result = out.value;
calloc.free(out);
calloc.free(nameC);
return out.value;
return result;
}
/// Write an existing in-memory reflog object back to disk using an atomic file

View file

@ -66,14 +66,15 @@ String transform({
final nameC = name.toNativeUtf8().cast<Int8>();
final error = libgit2.git_refspec_transform(out, refspecPointer, nameC);
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
libgit2.git_buf_dispose(out);
calloc.free(out);
calloc.free(nameC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
calloc.free(out);
return result;
}
}
@ -90,14 +91,15 @@ String rTransform({
final nameC = name.toNativeUtf8().cast<Int8>();
final error = libgit2.git_refspec_rtransform(out, refspecPointer, nameC);
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
libgit2.git_buf_dispose(out);
calloc.free(out);
calloc.free(nameC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
calloc.free(out);
return result;
}
}

View file

@ -9,8 +9,6 @@ import 'package:libgit2dart/src/oid.dart';
import 'package:libgit2dart/src/util.dart';
/// Get a list of the configured remotes for a repo.
///
/// Throws a [LibGit2Error] if error occured.
List<String> list(Pointer<git_repository> repo) {
final out = calloc<git_strarray>();
libgit2.git_remote_list(out, repo);
@ -38,13 +36,15 @@ Pointer<git_remote> lookup({
final nameC = name.toNativeUtf8().cast<Int8>();
final error = libgit2.git_remote_lookup(out, repoPointer, nameC);
final result = out.value;
calloc.free(out);
calloc.free(nameC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -62,14 +62,16 @@ Pointer<git_remote> create({
final urlC = url.toNativeUtf8().cast<Int8>();
final error = libgit2.git_remote_create(out, repoPointer, nameC, urlC);
final result = out.value;
calloc.free(out);
calloc.free(nameC);
calloc.free(urlC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -95,15 +97,17 @@ Pointer<git_remote> createWithFetchSpec({
fetchC,
);
final result = out.value;
calloc.free(out);
calloc.free(nameC);
calloc.free(urlC);
calloc.free(fetchC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}

View file

@ -5,6 +5,7 @@ import 'package:libgit2dart/libgit2dart.dart';
import 'package:libgit2dart/src/bindings/credentials.dart'
as credentials_bindings;
import 'package:libgit2dart/src/bindings/libgit2_bindings.dart';
import 'package:libgit2dart/src/bindings/remote.dart' as remote_bindings;
import 'package:libgit2dart/src/util.dart';
class RemoteCallbacks {
@ -65,11 +66,9 @@ class RemoteCallbacks {
return 0;
}
/// A function matching the
/// `Remote Function(Repository repo, String name, String url)` signature to
/// override the remote creation and customization process during a clone
/// operation.
static Remote Function(Repository, String, String)? remoteFunction;
/// Values used to override the remote creation and customization process
/// during a clone operation.
static RemoteCallback? remoteCbData;
/// A callback used to create the git remote, prior to its being used to
/// perform the clone operation.
@ -80,19 +79,31 @@ class RemoteCallbacks {
Pointer<Int8> url,
Pointer<Void> payload,
) {
remote[0] = remoteFunction!(
Repository(repo),
name.cast<Utf8>().toDartString(),
url.cast<Utf8>().toDartString(),
).pointer;
late final Pointer<git_remote> remotePointer;
if (remoteCbData!.fetch == null) {
remotePointer = remote_bindings.create(
repoPointer: repo,
name: remoteCbData!.name,
url: remoteCbData!.url,
);
} else {
remotePointer = remote_bindings.createWithFetchSpec(
repoPointer: repo,
name: remoteCbData!.name,
url: remoteCbData!.url,
fetch: remoteCbData!.fetch!,
);
}
remote[0] = remotePointer;
return 0;
}
/// A function matching the `Repository Function(String path, bool bare)`
/// signature to override the repository creation and customization process
/// Values used to override the repository creation and customization process
/// during a clone operation.
static Repository Function(String, bool)? repositoryFunction;
static RepositoryCallback? repositoryCbData;
/// A callback used to create the new repository into which to clone.
static int repositoryCb(
@ -101,11 +112,20 @@ class RemoteCallbacks {
int bare,
Pointer<Void> payload,
) {
repo[0] = repositoryFunction!(
path.cast<Utf8>().toDartString(),
bare == 1 || false,
final repoPointer = Repository.init(
path: repositoryCbData!.path,
bare: repositoryCbData!.bare,
flags: repositoryCbData!.flags,
mode: repositoryCbData!.mode,
workdirPath: repositoryCbData!.workdirPath,
description: repositoryCbData!.description,
templatePath: repositoryCbData!.templatePath,
initialHead: repositoryCbData!.initialHead,
originUrl: repositoryCbData!.originUrl,
).pointer;
repo[0] = repoPointer;
return 0;
}
@ -236,8 +256,8 @@ class RemoteCallbacks {
sidebandProgress = null;
updateTips = null;
pushUpdateReference = null;
remoteFunction = null;
repositoryFunction = null;
remoteCbData = null;
repositoryCbData = null;
credentials = null;
}
}

View file

@ -19,13 +19,15 @@ Pointer<git_repository> open(String path) {
final pathC = path.toNativeUtf8().cast<Int8>();
final error = libgit2.git_repository_open(out, pathC);
final result = out.value;
calloc.free(out);
calloc.free(pathC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -50,7 +52,10 @@ String discover({
calloc.free(ceilingDirsC);
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
libgit2.git_buf_dispose(out);
calloc.free(out);
return result;
}
@ -90,6 +95,9 @@ Pointer<git_repository> init({
final error = libgit2.git_repository_init_ext(out, pathC, opts);
final result = out.value;
calloc.free(out);
calloc.free(pathC);
calloc.free(workdirPathC);
calloc.free(descriptionC);
@ -99,10 +107,9 @@ Pointer<git_repository> init({
calloc.free(opts);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -113,8 +120,9 @@ Pointer<git_repository> clone({
required String url,
required String localPath,
required bool bare,
Remote Function(Repository, String, String)? remote,
Repository Function(String, bool)? repository,
RemoteCallback? remoteCallback,
// Repository Function(String, bool)? repository,
RepositoryCallback? repositoryCallback,
String? checkoutBranch,
required Callbacks callbacks,
}) {
@ -138,14 +146,14 @@ Pointer<git_repository> clone({
const except = -1;
git_remote_create_cb remoteCb = nullptr;
if (remote != null) {
RemoteCallbacks.remoteFunction = remote;
if (remoteCallback != null) {
RemoteCallbacks.remoteCbData = remoteCallback;
remoteCb = Pointer.fromFunction(RemoteCallbacks.remoteCb, except);
}
git_repository_create_cb repositoryCb = nullptr;
if (repository != null) {
RemoteCallbacks.repositoryFunction = repository;
if (repositoryCallback != null) {
RemoteCallbacks.repositoryCbData = repositoryCallback;
repositoryCb = Pointer.fromFunction(RemoteCallbacks.repositoryCb, except);
}
@ -157,6 +165,9 @@ Pointer<git_repository> clone({
final error = libgit2.git_clone(out, urlC, localPathC, cloneOptions);
final result = out.value;
calloc.free(out);
calloc.free(urlC);
calloc.free(localPathC);
calloc.free(checkoutBranchC);
@ -165,10 +176,9 @@ Pointer<git_repository> clone({
RemoteCallbacks.reset();
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -211,9 +221,9 @@ void setNamespace({
required Pointer<git_repository> repoPointer,
String? namespace,
}) {
final nmspace = namespace?.toNativeUtf8().cast<Int8>() ?? nullptr;
libgit2.git_repository_set_namespace(repoPointer, nmspace);
calloc.free(nmspace);
final namespaceC = namespace?.toNativeUtf8().cast<Int8>() ?? nullptr;
libgit2.git_repository_set_namespace(repoPointer, namespaceC);
calloc.free(namespaceC);
}
/// Check if a repository is bare or not.
@ -247,11 +257,14 @@ Pointer<git_reference> head(Pointer<git_repository> repo) {
final out = calloc<Pointer<git_reference>>();
final error = libgit2.git_repository_head(out, repo);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -337,7 +350,12 @@ Map<String, String> identity(Pointer<git_repository> repo) {
Pointer<git_config> config(Pointer<git_repository> repo) {
final out = calloc<Pointer<git_config>>();
libgit2.git_repository_config(out, repo);
return out.value;
final result = out.value;
calloc.free(out);
return result;
}
/// Get a snapshot of the repository's configuration.
@ -351,7 +369,12 @@ Pointer<git_config> config(Pointer<git_repository> repo) {
Pointer<git_config> configSnapshot(Pointer<git_repository> repo) {
final out = calloc<Pointer<git_config>>();
libgit2.git_repository_config_snapshot(out, repo);
return out.value;
final result = out.value;
calloc.free(out);
return result;
}
/// Get the Index file for this repository.
@ -363,7 +386,12 @@ Pointer<git_config> configSnapshot(Pointer<git_repository> repo) {
Pointer<git_index> index(Pointer<git_repository> repo) {
final out = calloc<Pointer<git_index>>();
libgit2.git_repository_index(out, repo);
return out.value;
final result = out.value;
calloc.free(out);
return result;
}
/// Determine if the repository was a shallow clone.
@ -392,12 +420,14 @@ String message(Pointer<git_repository> repo) {
final out = calloc<git_buf>();
final error = libgit2.git_repository_message(out, repo);
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
libgit2.git_buf_dispose(out);
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
final result = out.ref.ptr.cast<Utf8>().toDartString(length: out.ref.size);
calloc.free(out);
return result;
}
}
@ -419,11 +449,14 @@ Pointer<git_odb> odb(Pointer<git_repository> repo) {
final out = calloc<Pointer<git_odb>>();
final error = libgit2.git_repository_odb(out, repo);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -440,11 +473,14 @@ Pointer<git_refdb> refdb(Pointer<git_repository> repo) {
final out = calloc<Pointer<git_refdb>>();
final error = libgit2.git_repository_refdb(out, repo);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -516,15 +552,15 @@ void setWorkdir({
required String path,
required bool updateGitlink,
}) {
final workdir = path.toNativeUtf8().cast<Int8>();
final workdirC = path.toNativeUtf8().cast<Int8>();
final updateGitlinkC = updateGitlink ? 1 : 0;
final error = libgit2.git_repository_set_workdir(
repoPointer,
workdir,
workdirC,
updateGitlinkC,
);
calloc.free(workdir);
calloc.free(workdirC);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());

View file

@ -46,13 +46,15 @@ Pointer<git_object> revParseSingle({
final error = libgit2.git_revparse_single(out, repoPointer, specC);
final result = out.value;
calloc.free(out);
calloc.free(specC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -83,18 +85,19 @@ List<Pointer> revParseExt({
specC,
);
final result = <Pointer>[];
result.add(objectOut.value);
if (referenceOut.value != nullptr) {
result.add(referenceOut.value);
}
calloc.free(objectOut);
calloc.free(referenceOut);
calloc.free(specC);
if (error < 0) {
calloc.free(objectOut);
calloc.free(referenceOut);
throw LibGit2Error(libgit2.git_error_last());
} else {
final result = <Pointer>[];
result.add(objectOut.value);
if (referenceOut.value != nullptr) {
result.add(referenceOut.value);
}
return result;
}
}

View file

@ -23,11 +23,14 @@ Pointer<git_revwalk> create(Pointer<git_repository> repo) {
final out = calloc<Pointer<git_revwalk>>();
final error = libgit2.git_revwalk_new(out, repo);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -152,10 +155,10 @@ List<Pointer<git_commit>> walk({
oidPointer: oid,
);
result.add(commit);
calloc.free(oid);
} else {
break;
}
calloc.free(oid);
}
return result;

View file

@ -22,14 +22,16 @@ Pointer<git_signature> create({
final emailC = email.toNativeUtf8().cast<Int8>();
final error = libgit2.git_signature_new(out, nameC, emailC, time, offset);
final result = out.value;
calloc.free(out);
calloc.free(nameC);
calloc.free(emailC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -42,14 +44,16 @@ Pointer<git_signature> now({required String name, required String email}) {
final emailC = email.toNativeUtf8().cast<Int8>();
final error = libgit2.git_signature_now(out, nameC, emailC);
final result = out.value;
calloc.free(out);
calloc.free(nameC);
calloc.free(emailC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -61,7 +65,24 @@ Pointer<git_signature> now({required String name, required String email}) {
Pointer<git_signature> defaultSignature(Pointer<git_repository> repo) {
final out = calloc<Pointer<git_signature>>();
libgit2.git_signature_default(out, repo);
return out.value;
final result = out.value;
calloc.free(out);
return result;
}
/// Create a copy of an existing signature.
Pointer<git_signature> duplicate(Pointer<git_signature> sig) {
final out = calloc<Pointer<git_signature>>();
libgit2.git_signature_dup(out, sig);
final result = out.value;
calloc.free(out);
return result;
}
/// Free an existing signature.

View file

@ -13,11 +13,14 @@ Pointer<git_status_list> listNew(Pointer<git_repository> repo) {
final out = calloc<Pointer<git_status_list>>();
final error = libgit2.git_status_list_new(out, repo, nullptr);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -62,14 +65,14 @@ int file({required Pointer<git_repository> repoPointer, required String path}) {
final pathC = path.toNativeUtf8().cast<Int8>();
final error = libgit2.git_status_file(out, repoPointer, pathC);
final result = out.value;
calloc.free(out);
calloc.free(pathC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
final result = out.value;
calloc.free(out);
return result;
}
}

View file

@ -55,13 +55,15 @@ Pointer<git_submodule> lookup({
final error = libgit2.git_submodule_lookup(out, repoPointer, nameC);
final result = out.value;
calloc.free(out);
calloc.free(nameC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -130,11 +132,14 @@ Pointer<git_repository> open(Pointer<git_submodule> submodule) {
final out = calloc<Pointer<git_repository>>();
final error = libgit2.git_submodule_open(out, submodule);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -165,14 +170,16 @@ Pointer<git_submodule> addSetup({
useGitlinkC,
);
final result = out.value;
calloc.free(out);
calloc.free(urlC);
calloc.free(pathC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -229,10 +236,11 @@ int status({
final nameC = name.toNativeUtf8().cast<Int8>();
libgit2.git_submodule_status(out, repoPointer, nameC, ignore);
final result = out.value;
calloc.free(out);
calloc.free(nameC);
final result = out.value;
calloc.free(out);
return result;
}

View file

@ -36,11 +36,14 @@ Pointer<git_tag> lookup({
final out = calloc<Pointer<git_tag>>();
final error = libgit2.git_tag_lookup(out, repoPointer, oidPointer);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -54,11 +57,14 @@ Pointer<git_object> target(Pointer<git_tag> tag) {
final out = calloc<Pointer<git_object>>();
final error = libgit2.git_tag_target(out, tag);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -77,8 +83,10 @@ String name(Pointer<git_tag> tag) =>
libgit2.git_tag_name(tag).cast<Utf8>().toDartString();
/// Get the message of a tag.
String message(Pointer<git_tag> tag) =>
libgit2.git_tag_message(tag).cast<Utf8>().toDartString();
String message(Pointer<git_tag> tag) {
final result = libgit2.git_tag_message(tag);
return result == nullptr ? '' : result.cast<Utf8>().toDartString();
}
/// Get the tagger (author) of a tag.
Pointer<git_signature> tagger(Pointer<git_tag> tag) =>

View file

@ -18,11 +18,14 @@ Pointer<git_tree> lookup({
final out = calloc<Pointer<git_tree>>();
final error = libgit2.git_tree_lookup(out, repoPointer, oidPointer);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -82,13 +85,15 @@ Pointer<git_tree_entry> getByPath({
final pathC = path.toNativeUtf8().cast<Int8>();
final error = libgit2.git_tree_entry_bypath(out, rootPointer, pathC);
final result = out.value;
calloc.free(out);
calloc.free(pathC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}

View file

@ -24,11 +24,14 @@ Pointer<git_treebuilder> create({
final out = calloc<Pointer<git_treebuilder>>();
final error = libgit2.git_treebuilder_new(out, repoPointer, sourcePointer);
final result = out.value;
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}

View file

@ -33,15 +33,17 @@ Pointer<git_worktree> create({
final error = libgit2.git_worktree_add(out, repoPointer, nameC, pathC, opts);
final result = out.value;
calloc.free(out);
calloc.free(nameC);
calloc.free(pathC);
calloc.free(opts);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -56,13 +58,15 @@ Pointer<git_worktree> lookup({
final nameC = name.toNativeUtf8().cast<Int8>();
final error = libgit2.git_worktree_lookup(out, repoPointer, nameC);
final result = out.value;
calloc.free(out);
calloc.free(nameC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
return result;
}
}
@ -80,7 +84,11 @@ bool isPrunable(Pointer<git_worktree> wt) {
GIT_WORKTREE_PRUNE_OPTIONS_VERSION,
);
return libgit2.git_worktree_is_prunable(wt, opts) > 0 || false;
final result = libgit2.git_worktree_is_prunable(wt, opts);
calloc.free(opts);
return result > 0 || false;
}
/// Prune working tree.

View file

@ -34,8 +34,6 @@ class Blame with IterableMixin<BlameHunk> {
/// [maxLine] is the last line in the file to blame. The default is the last
/// line of the file.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Blame.file({
required Repository repo,
@ -57,6 +55,7 @@ class Blame with IterableMixin<BlameHunk> {
minLine: minLine,
maxLine: maxLine,
);
_finalizer.attach(this, _blamePointer, detach: this);
}
/// Returns blame data for a file that has been modified in memory. The
@ -74,6 +73,7 @@ class Blame with IterableMixin<BlameHunk> {
reference: reference._blamePointer,
buffer: buffer,
);
_finalizer.attach(this, _blamePointer, detach: this);
}
/// Pointer to memory address for allocated blame object.
@ -83,7 +83,7 @@ class Blame with IterableMixin<BlameHunk> {
///
/// Throws [RangeError] if index out of range.
BlameHunk operator [](int index) {
return BlameHunk(
return BlameHunk._(
bindings.getHunkByIndex(
blamePointer: _blamePointer,
index: index,
@ -96,7 +96,7 @@ class Blame with IterableMixin<BlameHunk> {
///
/// Throws [RangeError] if [lineNumber] is out of range.
BlameHunk forLine(int lineNumber) {
return BlameHunk(
return BlameHunk._(
bindings.getHunkByLine(
blamePointer: _blamePointer,
lineNumber: lineNumber,
@ -105,16 +105,25 @@ class Blame with IterableMixin<BlameHunk> {
}
/// Releases memory allocated for blame object.
void free() => bindings.free(_blamePointer);
void free() {
bindings.free(_blamePointer);
_finalizer.detach(this);
}
@override
Iterator<BlameHunk> get iterator => _BlameIterator(_blamePointer);
}
// coverage:ignore-start
final _finalizer = Finalizer<Pointer<git_blame>>(
(pointer) => bindings.free(pointer),
);
// coverage:ignore-end
class BlameHunk {
/// Initializes a new instance of the [BlameHunk] class from
/// provided pointer to blame hunk object in memory.
const BlameHunk(this._blameHunkPointer);
const BlameHunk._(this._blameHunkPointer);
/// Pointer to memory address for allocated blame hunk object.
final Pointer<git_blame_hunk> _blameHunkPointer;
@ -194,7 +203,7 @@ class _BlameIterator implements Iterator<BlameHunk> {
if (index == count) {
return false;
} else {
currentHunk = BlameHunk(
currentHunk = BlameHunk._(
bindings.getHunkByIndex(
blamePointer: _blamePointer,
index: index,

View file

@ -7,18 +7,17 @@ import 'package:libgit2dart/src/bindings/libgit2_bindings.dart';
class Blob {
/// Initializes a new instance of [Blob] class from provided pointer to
/// blob object in memory.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Blob(this._blobPointer);
Blob(this._blobPointer) {
_finalizer.attach(this, _blobPointer, detach: this);
}
/// Lookups a blob object for provided [oid] in a [repo]sitory.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Blob.lookup({required Repository repo, required Oid oid}) {
_blobPointer = bindings.lookup(
repoPointer: repo.pointer,
oidPointer: oid.pointer,
);
_finalizer.attach(this, _blobPointer, detach: this);
}
late final Pointer<git_blob> _blobPointer;
@ -80,8 +79,6 @@ class Blob {
int get size => bindings.size(_blobPointer);
/// Creates an in-memory copy of a blob.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Blob duplicate() => Blob(bindings.duplicate(_blobPointer));
/// Returns filtered content of a blob.
@ -114,10 +111,19 @@ class Blob {
}
/// Releases memory allocated for blob object.
void free() => bindings.free(_blobPointer);
void free() {
bindings.free(_blobPointer);
_finalizer.detach(this);
}
@override
String toString() {
return 'Blob{oid: $oid, isBinary: $isBinary, size: $size}';
}
}
// coverage:ignore-start
final _finalizer = Finalizer<Pointer<git_blob>>(
(pointer) => bindings.free(pointer),
);
// coverage:ignore-end

View file

@ -8,9 +8,9 @@ import 'package:libgit2dart/src/bindings/reference.dart' as reference_bindings;
class Branch {
/// Initializes a new instance of [Branch] class from provided pointer to
/// branch object in memory.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Branch(this._branchPointer);
Branch(this._branchPointer) {
_finalizer.attach(this, _branchPointer, detach: this);
}
/// Creates a new branch pointing at a [target] commit.
///
@ -24,8 +24,6 @@ class Branch {
/// [target] is the commit to which this branch should point. This object must
/// belong to the given [repo].
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Branch.create({
required Repository repo,
@ -39,6 +37,7 @@ class Branch {
targetPointer: target.pointer,
force: force,
);
_finalizer.attach(this, _branchPointer, detach: this);
}
/// Lookups a branch by its [name] and [type] in a [repo]sitory. Lookups in
@ -49,8 +48,6 @@ class Branch {
/// If branch [type] is [GitBranch.remote] you must include the remote name
/// in the [name] (e.g. "origin/master").
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Branch.lookup({
required Repository repo,
@ -62,6 +59,7 @@ class Branch {
branchName: name,
branchType: type.value,
);
_finalizer.attach(this, _branchPointer, detach: this);
}
late final Pointer<git_reference> _branchPointer;
@ -72,9 +70,6 @@ class Branch {
/// Returns a list of branches that can be found in a [repo]sitory for
/// provided [type]. Default is all branches (local and remote).
///
/// **IMPORTANT**: Branches must be freed manually when no longer needed to
/// prevent memory leak.
///
/// Throws a [LibGit2Error] if error occured.
static List<Branch> list({
required Repository repo,
@ -94,7 +89,6 @@ class Branch {
static void delete({required Repository repo, required String name}) {
final branch = Branch.lookup(repo: repo, name: name);
bindings.delete(branch.pointer);
branch.free();
}
/// Renames an existing local branch reference with provided [oldName].
@ -117,8 +111,6 @@ class Branch {
newBranchName: newName,
force: force,
);
branch.free();
}
/// [Oid] pointed to by a branch.
@ -164,8 +156,6 @@ class Branch {
/// Upstream [Reference] of a local branch.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Reference get upstream => Reference(bindings.getUpstream(_branchPointer));
@ -222,7 +212,10 @@ class Branch {
}
/// Releases memory allocated for branch object.
void free() => bindings.free(_branchPointer);
void free() {
bindings.free(_branchPointer);
_finalizer.detach(this);
}
@override
String toString() {
@ -230,3 +223,9 @@ class Branch {
'isCheckedOut: $isCheckedOut}';
}
}
// coverage:ignore-start
final _finalizer = Finalizer<Pointer<git_reference>>(
(pointer) => bindings.free(pointer),
);
// coverage:ignore-end

View file

@ -116,7 +116,6 @@ class Checkout {
);
object_bindings.free(treeish);
ref.free();
}
/// Updates files in the working tree to match the content of the tree

View file

@ -8,18 +8,17 @@ import 'package:libgit2dart/src/bindings/libgit2_bindings.dart';
class Commit {
/// Initializes a new instance of [Commit] class from provided pointer to
/// commit object in memory.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Commit(this._commitPointer);
Commit(this._commitPointer) {
_finalizer.attach(this, _commitPointer, detach: this);
}
/// Lookups commit object for provided [oid] in the [repo]sitory.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Commit.lookup({required Repository repo, required Oid oid}) {
_commitPointer = bindings.lookup(
repoPointer: repo.pointer,
oidPointer: oid.pointer,
);
_finalizer.attach(this, _commitPointer, detach: this);
}
late final Pointer<git_commit> _commitPointer;
@ -194,8 +193,6 @@ class Commit {
///
/// [mainline] is parent of the commit if it is a merge (i.e. 1, 2).
///
/// **IMPORTANT**: produced index should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Index revertTo({
required Commit commit,
@ -221,7 +218,7 @@ class Commit {
/// leading newlines.
String get message => bindings.message(_commitPointer);
/// Returns the short "summary" of the git commit message.
/// Short "summary" of the git commit message.
///
/// The returned message is the summary of the commit, comprising the first
/// paragraph of the message with whitespace trimmed and squashed.
@ -229,7 +226,7 @@ class Commit {
/// Throws a [LibGit2Error] if error occured.
String get summary => bindings.summary(_commitPointer);
/// Returns the long "body" of the commit message.
/// Long "body" of the commit message.
///
/// The returned message is the body of the commit, comprising everything but
/// the first paragraph of the message. Leading and trailing whitespaces are
@ -272,8 +269,6 @@ class Commit {
/// Returns the specified parent of the commit at provided 0-based [position].
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Commit parent(int position) {
return Commit(
@ -303,8 +298,6 @@ class Commit {
/// Passing 0 as the generation number returns another instance of the base
/// commit itself.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Commit nthGenAncestor(int n) {
return Commit(bindings.nthGenAncestor(commitPointer: _commitPointer, n: n));
@ -323,12 +316,13 @@ class Commit {
}
/// Creates an in-memory copy of a commit.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Commit duplicate() => Commit(bindings.duplicate(_commitPointer));
/// Releases memory allocated for commit object.
void free() => bindings.free(_commitPointer);
void free() {
bindings.free(_commitPointer);
_finalizer.detach(this);
}
@override
String toString() {
@ -337,3 +331,9 @@ class Commit {
' author: $author}';
}
}
// coverage:ignore-start
final _finalizer = Finalizer<Pointer<git_commit>>(
(pointer) => bindings.free(pointer),
);
// coverage:ignore-end

View file

@ -11,9 +11,9 @@ import 'package:libgit2dart/src/util.dart';
class Config with IterableMixin<ConfigEntry> {
/// Initializes a new instance of [Config] class from provided
/// pointer to config object in memory.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Config(this._configPointer);
Config(this._configPointer) {
_finalizer.attach(this, _configPointer, detach: this);
}
/// Opens config file at provided [path].
///
@ -23,8 +23,6 @@ class Config with IterableMixin<ConfigEntry> {
/// Git config file following the default Git config syntax (see
/// `man git-config`).
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws an [Exception] if file not found at provided path.
Config.open([String? path]) {
libgit2.git_libgit2_init();
@ -38,39 +36,44 @@ class Config with IterableMixin<ConfigEntry> {
throw Exception('File not found');
}
}
_finalizer.attach(this, _configPointer, detach: this);
}
/// Opens the system configuration file.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Config.system() {
libgit2.git_libgit2_init();
_configPointer = bindings.open(bindings.findSystem());
// coverage:ignore-start
_finalizer.attach(this, _configPointer, detach: this);
// coverage:ignore-end
}
/// Opens the global configuration file.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Config.global() {
libgit2.git_libgit2_init();
_configPointer = bindings.open(bindings.findGlobal());
// coverage:ignore-start
_finalizer.attach(this, _configPointer, detach: this);
// coverage:ignore-end
}
/// Opens the global XDG configuration file.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Config.xdg() {
libgit2.git_libgit2_init();
_configPointer = bindings.open(bindings.findXdg());
// coverage:ignore-start
_finalizer.attach(this, _configPointer, detach: this);
// coverage:ignore-end
}
/// Pointer to memory address for allocated config object.
@ -83,11 +86,24 @@ class Config with IterableMixin<ConfigEntry> {
/// Returns the [ConfigEntry] of a [variable].
ConfigEntry operator [](String variable) {
return ConfigEntry(
bindings.getEntry(
configPointer: _configPointer,
variable: variable,
),
final entryPointer = bindings.getEntry(
configPointer: _configPointer,
variable: variable,
);
final name = entryPointer.ref.name.cast<Utf8>().toDartString();
final value = entryPointer.ref.value.cast<Utf8>().toDartString();
final includeDepth = entryPointer.ref.include_depth;
final level = GitConfigLevel.values.singleWhere(
(e) => entryPointer.ref.level == e.value,
);
bindings.freeEntry(entryPointer);
return ConfigEntry._(
name: name,
value: value,
includeDepth: includeDepth,
level: level,
);
}
@ -167,36 +183,41 @@ class Config with IterableMixin<ConfigEntry> {
}
/// Releases memory allocated for config object.
void free() => bindings.free(_configPointer);
void free() {
bindings.free(_configPointer);
_finalizer.detach(this);
}
@override
Iterator<ConfigEntry> get iterator =>
_ConfigIterator(bindings.iterator(_configPointer));
}
class ConfigEntry {
/// Initializes a new instance of [ConfigEntry] class from provided
/// pointer to config entry object in memory.
const ConfigEntry(this._configEntryPointer);
// coverage:ignore-start
final _finalizer = Finalizer<Pointer<git_config>>(
(pointer) => bindings.free(pointer),
);
// coverage:ignore-end
/// Pointer to memory address for allocated config entry object.
final Pointer<git_config_entry> _configEntryPointer;
class ConfigEntry {
ConfigEntry._({
required this.name,
required this.value,
required this.includeDepth,
required this.level,
});
/// Name of the entry (normalised).
String get name => _configEntryPointer.ref.name.cast<Utf8>().toDartString();
final String name;
/// Value of the entry.
String get value => _configEntryPointer.ref.value.cast<Utf8>().toDartString();
final String value;
/// Depth of includes where this variable was found
int get includeDepth => _configEntryPointer.ref.include_depth;
final int includeDepth;
/// Which config file this was found in.
GitConfigLevel get level {
return GitConfigLevel.values.singleWhere(
(e) => _configEntryPointer.ref.level == e.value,
);
}
final GitConfigLevel level;
@override
String toString() {
@ -206,7 +227,9 @@ class ConfigEntry {
}
class _ConfigIterator implements Iterator<ConfigEntry> {
_ConfigIterator(this._iteratorPointer);
_ConfigIterator(this._iteratorPointer) {
_iteratorFinalizer.attach(this, _iteratorPointer);
}
/// Pointer to memory address for allocated config iterator.
final Pointer<git_config_iterator> _iteratorPointer;
@ -225,7 +248,20 @@ class _ConfigIterator implements Iterator<ConfigEntry> {
} else {
error = libgit2.git_config_next(entry, _iteratorPointer);
if (error != -31) {
_currentEntry = ConfigEntry(entry.value);
final name = entry.value.ref.name.cast<Utf8>().toDartString();
final value = entry.value.ref.value.cast<Utf8>().toDartString();
final includeDepth = entry.value.ref.include_depth;
final level = GitConfigLevel.values.singleWhere(
(e) => entry.value.ref.level == e.value,
);
_currentEntry = ConfigEntry._(
name: name,
value: value,
includeDepth: includeDepth,
level: level,
);
return true;
} else {
return false;
@ -233,3 +269,9 @@ class _ConfigIterator implements Iterator<ConfigEntry> {
}
}
}
// coverage:ignore-start
final _iteratorFinalizer = Finalizer<Pointer<git_config_iterator>>(
(pointer) => bindings.freeIterator(pointer),
);
// coverage:ignore-end

View file

@ -4,15 +4,14 @@ import 'package:ffi/ffi.dart';
import 'package:libgit2dart/libgit2dart.dart';
import 'package:libgit2dart/src/bindings/diff.dart' as bindings;
import 'package:libgit2dart/src/bindings/libgit2_bindings.dart';
import 'package:libgit2dart/src/bindings/patch.dart' as patch_bindings;
import 'package:libgit2dart/src/util.dart';
class Diff {
/// Initializes a new instance of [Diff] class from provided
/// pointer to diff object in memory.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Diff(this._diffPointer);
Diff(this._diffPointer) {
_finalizer.attach(this, _diffPointer, detach: this);
}
/// Creates a diff between the [repo]sitory [index] and the workdir directory.
///
@ -30,8 +29,6 @@ class Diff {
/// [interhunkLines] is the maximum number of unchanged lines between hunk
/// boundaries before the hunks will be merged into one. Defaults to 0.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Diff.indexToWorkdir({
required Repository repo,
@ -47,6 +44,7 @@ class Diff {
contextLines: contextLines,
interhunkLines: interhunkLines,
);
_finalizer.attach(this, _diffPointer, detach: this);
}
/// Creates a diff between a [tree] and [repo]sitory [index].
@ -83,6 +81,7 @@ class Diff {
contextLines: contextLines,
interhunkLines: interhunkLines,
);
_finalizer.attach(this, _diffPointer, detach: this);
}
/// Creates a diff between a [tree] and the working directory.
@ -124,6 +123,7 @@ class Diff {
contextLines: contextLines,
interhunkLines: interhunkLines,
);
_finalizer.attach(this, _diffPointer, detach: this);
}
/// Creates a diff between a [tree] and the working directory using index
@ -145,8 +145,6 @@ class Diff {
/// [interhunkLines] is the maximum number of unchanged lines between hunk
/// boundaries before the hunks will be merged into one. Defaults to 0.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Diff.treeToWorkdirWithIndex({
required Repository repo,
@ -162,6 +160,7 @@ class Diff {
contextLines: contextLines,
interhunkLines: interhunkLines,
);
_finalizer.attach(this, _diffPointer, detach: this);
}
/// Creates a diff with the difference between two [Tree] objects.
@ -204,6 +203,7 @@ class Diff {
contextLines: contextLines,
interhunkLines: interhunkLines,
);
_finalizer.attach(this, _diffPointer, detach: this);
}
/// Creates a diff with the difference between two [Index] objects.
@ -239,6 +239,7 @@ class Diff {
contextLines: contextLines,
interhunkLines: interhunkLines,
);
_finalizer.attach(this, _diffPointer, detach: this);
}
/// Reads the [content]s of a git patch file into a git diff object.
@ -255,6 +256,7 @@ class Diff {
Diff.parse(String content) {
libgit2.git_libgit2_init();
_diffPointer = bindings.parse(content);
_finalizer.attach(this, _diffPointer, detach: this);
}
late final Pointer<git_diff> _diffPointer;
@ -441,7 +443,10 @@ class Diff {
Oid get patchOid => Oid(bindings.patchOid(_diffPointer));
/// Releases memory allocated for diff object.
void free() => bindings.free(_diffPointer);
void free() {
bindings.free(_diffPointer);
_finalizer.detach(this);
}
@override
String toString() {
@ -449,6 +454,12 @@ class Diff {
}
}
// coverage:ignore-start
final _finalizer = Finalizer<Pointer<git_diff>>(
(pointer) => bindings.free(pointer),
);
// coverage:ignore-end
class DiffDelta {
/// Initializes a new instance of [DiffDelta] class from provided
/// pointer to diff delta object in memory.
@ -487,10 +498,10 @@ class DiffDelta {
int get numberOfFiles => _diffDeltaPointer.ref.nfiles;
/// Represents the "from" side of the diff.
DiffFile get oldFile => DiffFile(_diffDeltaPointer.ref.old_file);
DiffFile get oldFile => DiffFile._(_diffDeltaPointer.ref.old_file);
/// Represents the "to" side of the diff.
DiffFile get newFile => DiffFile(_diffDeltaPointer.ref.new_file);
DiffFile get newFile => DiffFile._(_diffDeltaPointer.ref.new_file);
@override
String toString() {
@ -507,7 +518,7 @@ class DiffDelta {
class DiffFile {
/// Initializes a new instance of [DiffFile] class from provided diff file
/// object.
const DiffFile(this._diffFile);
const DiffFile._(this._diffFile);
final git_diff_file _diffFile;
@ -543,9 +554,9 @@ class DiffFile {
class DiffStats {
/// Initializes a new instance of [DiffStats] class from provided
/// pointer to diff stats object in memory.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
const DiffStats(this._diffStatsPointer);
DiffStats(this._diffStatsPointer) {
_statsFinalizer.attach(this, _diffStatsPointer, detach: this);
}
/// Pointer to memory address for allocated diff delta object.
final Pointer<git_diff_stats> _diffStatsPointer;
@ -573,7 +584,10 @@ class DiffStats {
}
/// Releases memory allocated for diff stats object.
void free() => bindings.statsFree(_diffStatsPointer);
void free() {
bindings.statsFree(_diffStatsPointer);
_statsFinalizer.detach(this);
}
@override
String toString() {
@ -582,111 +596,8 @@ class DiffStats {
}
}
class DiffHunk {
/// Initializes a new instance of [DiffHunk] class from provided
/// pointers to patch object and diff hunk object in memory and number of
/// lines in hunk.
const DiffHunk(
this._patchPointer,
this._diffHunkPointer,
this.linesCount,
this.index,
);
/// Pointer to memory address for allocated diff hunk object.
final Pointer<git_diff_hunk> _diffHunkPointer;
/// Pointer to memory address for allocated patch object.
final Pointer<git_patch> _patchPointer;
/// Number of total lines in this hunk.
final int linesCount;
/// Index of this hunk in the patch.
final int index;
/// Starting line number in 'old file'.
int get oldStart => _diffHunkPointer.ref.old_start;
/// Number of lines in 'old file'.
int get oldLines => _diffHunkPointer.ref.old_lines;
/// Starting line number in 'new file'.
int get newStart => _diffHunkPointer.ref.new_start;
/// Number of lines in 'new file'.
int get newLines => _diffHunkPointer.ref.new_lines;
/// Header of a hunk.
String get header {
final list = <int>[];
for (var i = 0; i < _diffHunkPointer.ref.header_len; i++) {
list.add(_diffHunkPointer.ref.header[i]);
}
return String.fromCharCodes(list);
}
/// List of lines in a hunk of a patch.
List<DiffLine> get lines {
final lines = <DiffLine>[];
for (var i = 0; i < linesCount; i++) {
lines.add(
DiffLine(
patch_bindings.lines(
patchPointer: _patchPointer,
hunkIndex: index,
lineOfHunk: i,
),
),
);
}
return lines;
}
@override
String toString() {
return 'DiffHunk{linesCount: $linesCount, index: $index, '
'oldStart: $oldStart, oldLines: $oldLines, newStart: $newStart, '
'newLines: $newLines, header: $header}';
}
}
class DiffLine {
/// Initializes a new instance of [DiffLine] class from provided
/// pointer to diff line object in memory.
const DiffLine(this._diffLinePointer);
/// Pointer to memory address for allocated diff line object.
final Pointer<git_diff_line> _diffLinePointer;
/// Type of the line.
GitDiffLine get origin {
return GitDiffLine.values.singleWhere(
(e) => _diffLinePointer.ref.origin == e.value,
);
}
/// Line number in old file or -1 for added line.
int get oldLineNumber => _diffLinePointer.ref.old_lineno;
/// Line number in new file or -1 for deleted line.
int get newLineNumber => _diffLinePointer.ref.new_lineno;
/// Number of newline characters in content.
int get numLines => _diffLinePointer.ref.num_lines;
/// Offset in the original file to the content.
int get contentOffset => _diffLinePointer.ref.content_offset;
/// Content of the diff line.
String get content => _diffLinePointer.ref.content
.cast<Utf8>()
.toDartString(length: _diffLinePointer.ref.content_len);
@override
String toString() {
return 'DiffLine{oldLineNumber: $oldLineNumber, '
'newLineNumber: $newLineNumber, numLines: $numLines, '
'contentOffset: $contentOffset, content: $content}';
}
}
// coverage:ignore-start
final _statsFinalizer = Finalizer<Pointer<git_diff_stats>>(
(pointer) => bindings.statsFree(pointer),
);
// coverage:ignore-end

View file

@ -9,19 +9,20 @@ import 'package:libgit2dart/src/bindings/libgit2_bindings.dart';
class Index with IterableMixin<IndexEntry> {
/// Initializes a new instance of [Index] class from provided
/// pointer to index object in memory.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
const Index(this._indexPointer);
Index(this._indexPointer) {
_finalizer.attach(this, _indexPointer, detach: this);
}
/// Creates an in-memory index object.
///
/// This index object cannot be read/written to the filesystem, but may be
/// used to perform in-memory index operations.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Index.newInMemory() : _indexPointer = bindings.newInMemory();
Index.newInMemory() {
_indexPointer = bindings.newInMemory();
_finalizer.attach(this, _indexPointer, detach: this);
}
final Pointer<git_index> _indexPointer;
late final Pointer<git_index> _indexPointer;
/// Pointer to memory address for allocated index object.
Pointer<git_index> get pointer => _indexPointer;
@ -300,7 +301,10 @@ class Index with IterableMixin<IndexEntry> {
bindings.removeAll(indexPointer: _indexPointer, pathspec: path);
/// Releases memory allocated for index object.
void free() => bindings.free(_indexPointer);
void free() {
bindings.free(_indexPointer);
_finalizer.detach(this);
}
@override
String toString() => 'Index{hasConflicts: $hasConflicts}';
@ -309,6 +313,12 @@ class Index with IterableMixin<IndexEntry> {
Iterator<IndexEntry> get iterator => _IndexIterator(_indexPointer);
}
// coverage:ignore-start
final _finalizer = Finalizer<Pointer<git_index>>(
(pointer) => bindings.free(pointer),
);
// coverage:ignore-end
class IndexEntry {
/// Initializes a new instance of [IndexEntry] class.
const IndexEntry(this._indexEntryPointer);

View file

@ -8,7 +8,7 @@ import 'package:libgit2dart/src/util.dart';
class Libgit2 {
Libgit2._(); // coverage:ignore-line
/// Returns libgit2 version number.
/// Libgit2 version number.
static String get version {
libgit2.git_libgit2_init();
@ -26,7 +26,7 @@ class Libgit2 {
return version;
}
/// Returns list of options libgit2 was compiled with.
/// Options libgit2 was compiled with.
static Set<GitFeature> get features {
libgit2.git_libgit2_init();
final featuresInt = libgit2.git_libgit2_features();
@ -35,15 +35,19 @@ class Libgit2 {
.toSet();
}
/// Returns owner validation setting for repository directories.
/// Owner validation setting for repository directories.
static bool get ownerValidation {
libgit2.git_libgit2_init();
final out = calloc<Int8>();
libgit2.git_libgit2_opts(
git_libgit2_opt_t.GIT_OPT_GET_OWNER_VALIDATION,
out,
);
return out.value == 1 || false;
final result = out.value;
calloc.free(out);
return result == 1 || false;
}
/// Sets owner validation setting for repository directories.

View file

@ -9,21 +9,19 @@ class Mailmap {
///
/// This object is empty, so you'll have to add a mailmap file before you can
/// do anything with it.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Mailmap.empty() {
libgit2.git_libgit2_init();
_mailmapPointer = bindings.init();
_finalizer.attach(this, _mailmapPointer, detach: this);
}
/// Initializes a new instance of [Mailmap] class from provided buffer.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Mailmap.fromBuffer(String buffer) {
libgit2.git_libgit2_init();
_mailmapPointer = bindings.fromBuffer(buffer);
_finalizer.attach(this, _mailmapPointer, detach: this);
}
/// Initializes a new instance of [Mailmap] class from a [repo]sitory, loading
@ -34,14 +32,13 @@ class Mailmap {
/// 1. `.mailmap` in the root of the repository's working directory, if
/// present.
/// 2. The blob object identified by the `mailmap.blob` config entry, if set.
/// NOTE: `mailmap.blob` defaults to `HEAD:.mailmap` in bare repositories
/// NOTE: `mailmap.blob` defaults to `HEAD:.mailmap` in bare repositories.
/// 3. The path in the `mailmap.file` config entry, if set.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Mailmap.fromRepository(Repository repo) {
_mailmapPointer = bindings.fromRepository(repo.pointer);
_finalizer.attach(this, _mailmapPointer, detach: this);
}
/// Pointer to memory address for allocated mailmap object.
@ -94,5 +91,14 @@ class Mailmap {
}
/// Releases memory allocated for mailmap object.
void free() => bindings.free(_mailmapPointer);
void free() {
bindings.free(_mailmapPointer);
_finalizer.detach(this);
}
}
// coverage:ignore-start
final _finalizer = Finalizer<Pointer<git_mailmap>>(
(pointer) => bindings.free(pointer),
);
// coverage:ignore-end

View file

@ -74,9 +74,6 @@ class Merge {
(e) => analysisInt[1] == e.value,
);
head.free();
ref.free();
return <Object>[analysisSet, mergePreference];
}
@ -140,8 +137,6 @@ class Merge {
/// [fileFlags] is a combination of [GitMergeFileFlag] flags. Defaults to
/// [GitMergeFileFlag.defaults].
///
/// **IMPORTANT**: returned index should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
static Index commits({
required Repository repo,
@ -188,8 +183,6 @@ class Merge {
/// [fileFlags] is a combination of [GitMergeFileFlag] flags. Defaults to
/// [GitMergeFileFlag.defaults].
///
/// **IMPORTANT**: returned index should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
static Index trees({
required Repository repo,

View file

@ -6,7 +6,9 @@ import 'package:libgit2dart/src/bindings/note.dart' as bindings;
class Note {
/// Initializes a new instance of the [Note] class from provided
/// pointer to note and annotatedOid objects in memory.
Note(this._notePointer, this._annotatedOidPointer);
Note(this._notePointer, this._annotatedOidPointer) {
_finalizer.attach(this, _notePointer, detach: this);
}
/// Lookups the note for an [annotatedOid].
///
@ -16,8 +18,6 @@ class Note {
///
/// [notesRef] is the canonical name of the reference to use. Defaults to "refs/notes/commits".
///
/// **IMPORTANT**: Notes must be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Note.lookup({
required Repository repo,
@ -30,6 +30,7 @@ class Note {
notesRef: notesRef,
);
_annotatedOidPointer = annotatedOid.pointer;
_finalizer.attach(this, _notePointer, detach: this);
}
/// Pointer to memory address for allocated note object.
@ -107,8 +108,6 @@ class Note {
/// Returns list of notes for [repo]sitory.
///
/// **IMPORTANT**: Notes must be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
static List<Note> list(Repository repo) {
final notesPointers = bindings.list(repo.pointer);
@ -132,10 +131,19 @@ class Note {
Oid get annotatedOid => Oid(_annotatedOidPointer);
/// Releases memory allocated for note object.
void free() => bindings.free(_notePointer);
void free() {
bindings.free(_notePointer);
_finalizer.detach(this);
}
@override
String toString() {
return 'Note{oid: $oid, message: $message, annotatedOid: $annotatedOid}';
}
}
// coverage:ignore-start
final _finalizer = Finalizer<Pointer<git_note>>(
(pointer) => bindings.free(pointer),
);
// coverage:ignore-end

View file

@ -7,20 +7,19 @@ import 'package:libgit2dart/src/util.dart';
class Odb {
/// Initializes a new instance of [Odb] class from provided
/// pointer to Odb object in memory.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Odb(this._odbPointer);
Odb(this._odbPointer) {
_finalizer.attach(this, _odbPointer, detach: this);
}
/// Creates a new object database with no backends.
///
/// Before the ODB can be used for read/writing, a custom database backend must be
/// manually added.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Odb.create() {
libgit2.git_libgit2_init();
_odbPointer = bindings.create();
_finalizer.attach(this, _odbPointer, detach: this);
}
late final Pointer<git_odb> _odbPointer;
@ -59,12 +58,9 @@ class Odb {
/// This method queries all available ODB backends trying to read the given
/// [oid].
///
/// **IMPORTANT**: Returned object should be freed to release allocated
/// memory.
///
/// Throws a [LibGit2Error] if error occured.
OdbObject read(Oid oid) {
return OdbObject(
return OdbObject._(
bindings.read(
odbPointer: _odbPointer,
oidPointer: oid.pointer,
@ -97,13 +93,24 @@ class Odb {
}
/// Releases memory allocated for odb object.
void free() => bindings.free(_odbPointer);
void free() {
bindings.free(_odbPointer);
_finalizer.detach(this);
}
}
// coverage:ignore-start
final _finalizer = Finalizer<Pointer<git_odb>>(
(pointer) => bindings.free(pointer),
);
// coverage:ignore-end
class OdbObject {
/// Initializes a new instance of the [OdbObject] class from
/// provided pointer to odbObject object in memory.
const OdbObject(this._odbObjectPointer);
OdbObject._(this._odbObjectPointer) {
_objectfinalizer.attach(this, _odbObjectPointer, detach: this);
}
/// Pointer to memory address for allocated odbObject object.
final Pointer<git_odb_object> _odbObjectPointer;
@ -124,10 +131,19 @@ class OdbObject {
int get size => bindings.objectSize(_odbObjectPointer);
/// Releases memory allocated for odbObject object.
void free() => bindings.objectFree(_odbObjectPointer);
void free() {
bindings.objectFree(_odbObjectPointer);
_objectfinalizer.detach(this);
}
@override
String toString() {
return 'OdbObject{oid: $oid, type: $type, size: $size}';
}
}
// coverage:ignore-start
final _objectfinalizer = Finalizer<Pointer<git_odb_object>>(
(pointer) => bindings.objectFree(pointer),
);
// coverage:ignore-end

View file

@ -25,13 +25,11 @@ class Oid {
if (sha.length == 40) {
_oidPointer = bindings.fromSHA(sha);
} else {
final odb = repo.odb;
_oidPointer = odb_bindings.existsPrefix(
odbPointer: odb.pointer,
odbPointer: repo.odb.pointer,
shortOidPointer: bindings.fromStrN(sha),
length: sha.length,
);
odb.free();
}
} else {
throw ArgumentError.value('$sha is not a valid sha hex string');

View file

@ -6,11 +6,10 @@ import 'package:libgit2dart/src/bindings/packbuilder.dart' as bindings;
class PackBuilder {
/// Initializes a new instance of [PackBuilder] class.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
PackBuilder(Repository repo) {
_packbuilderPointer = bindings.init(repo.pointer);
_finalizer.attach(this, _packbuilderPointer, detach: this);
}
/// Pointer to memory address for allocated packbuilder object.
@ -108,10 +107,19 @@ class PackBuilder {
}
/// Releases memory allocated for packbuilder object.
void free() => bindings.free(_packbuilderPointer);
void free() {
bindings.free(_packbuilderPointer);
_finalizer.detach(this);
}
@override
String toString() {
return 'PackBuilder{length: $length, writtenLength: $writtenLength}';
}
}
// coverage:ignore-start
final _finalizer = Finalizer<Pointer<git_packbuilder>>(
(pointer) => bindings.free(pointer),
);
// coverage:ignore-end

View file

@ -1,5 +1,6 @@
import 'dart:ffi';
import 'package:ffi/ffi.dart';
import 'package:libgit2dart/libgit2dart.dart';
import 'package:libgit2dart/src/bindings/libgit2_bindings.dart';
import 'package:libgit2dart/src/bindings/patch.dart' as bindings;
@ -8,9 +9,9 @@ import 'package:libgit2dart/src/util.dart';
class Patch {
/// Initializes a new instance of [Patch] class from provided
/// pointer to patch object in memory and pointers to old and new blobs/buffers.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Patch(this._patchPointer);
Patch(this._patchPointer) {
_finalizer.attach(this, _patchPointer, detach: this);
}
/// Directly generates a [Patch] from the difference between two blobs.
///
@ -30,8 +31,6 @@ class Patch {
/// [interhunkLines] is the maximum number of unchanged lines between hunk
/// boundaries before the hunks will be merged into one. Defaults to 0.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Patch.fromBlobs({
required Blob? oldBlob,
@ -51,6 +50,7 @@ class Patch {
contextLines: contextLines,
interhunkLines: interhunkLines,
);
_finalizer.attach(this, _patchPointer, detach: this);
}
/// Directly generates a [Patch] from the difference between the blob and a
@ -72,8 +72,6 @@ class Patch {
/// [interhunkLines] is the maximum number of unchanged lines between hunk
/// boundaries before the hunks will be merged into one. Defaults to 0.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Patch.fromBlobAndBuffer({
required Blob? blob,
@ -93,6 +91,7 @@ class Patch {
contextLines: contextLines,
interhunkLines: interhunkLines,
);
_finalizer.attach(this, _patchPointer, detach: this);
}
/// Directly generates a [Patch] from the difference between two buffers
@ -113,8 +112,6 @@ class Patch {
/// [interhunkLines] is the maximum number of unchanged lines between hunk
/// boundaries before the hunks will be merged into one. Defaults to 0.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Patch.fromBuffers({
required String? oldBuffer,
@ -136,6 +133,7 @@ class Patch {
contextLines: contextLines,
interhunkLines: interhunkLines,
);
_finalizer.attach(this, _patchPointer, detach: this);
}
/// Creates a patch for an entry in the diff list.
@ -144,11 +142,10 @@ class Patch {
///
/// [index] is the position of an entry in diff list.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Patch.fromDiff({required Diff diff, required int index}) {
_patchPointer = bindings.fromDiff(diffPointer: diff.pointer, index: index);
_finalizer.attach(this, _patchPointer, detach: this);
}
late final Pointer<git_patch> _patchPointer;
@ -157,7 +154,7 @@ class Patch {
PatchStats get stats {
final result = bindings.lineStats(_patchPointer);
return PatchStats(
return PatchStats._(
context: result['context']!,
insertions: result['insertions']!,
deletions: result['deletions']!,
@ -201,14 +198,49 @@ class Patch {
final length = bindings.numHunks(_patchPointer);
final hunks = <DiffHunk>[];
for (var i = 0; i < length; i++) {
final hunk = bindings.hunk(patchPointer: _patchPointer, hunkIndex: i);
for (var index = 0; index < length; index++) {
final hunk = bindings.hunk(patchPointer: _patchPointer, hunkIndex: index);
final hunkPointer = hunk['hunk']! as Pointer<git_diff_hunk>;
final linesCount = hunk['linesN']! as int;
final lines = <DiffLine>[];
for (var i = 0; i < linesCount; i++) {
final linePointer = bindings.lines(
patchPointer: _patchPointer,
hunkIndex: index,
lineOfHunk: i,
);
lines.add(
DiffLine._(
origin: GitDiffLine.values.singleWhere(
(e) => linePointer.ref.origin == e.value,
),
oldLineNumber: linePointer.ref.old_lineno,
newLineNumber: linePointer.ref.new_lineno,
numLines: linePointer.ref.num_lines,
contentOffset: linePointer.ref.content_offset,
content: linePointer.ref.content
.cast<Utf8>()
.toDartString(length: linePointer.ref.content_len),
),
);
}
final intHeader = <int>[];
for (var i = 0; i < hunkPointer.ref.header_len; i++) {
intHeader.add(hunkPointer.ref.header[i]);
}
hunks.add(
DiffHunk(
_patchPointer,
hunk['hunk']! as Pointer<git_diff_hunk>,
hunk['linesN']! as int,
i,
DiffHunk._(
linesCount: linesCount,
index: index,
oldStart: hunkPointer.ref.old_start,
oldLines: hunkPointer.ref.old_lines,
newStart: hunkPointer.ref.new_start,
newLines: hunkPointer.ref.new_lines,
header: String.fromCharCodes(intHeader),
lines: lines,
),
);
}
@ -217,15 +249,24 @@ class Patch {
}
/// Releases memory allocated for patch object.
void free() => bindings.free(_patchPointer);
void free() {
bindings.free(_patchPointer);
_finalizer.detach(this);
}
@override
String toString() => 'Patch{size: ${size()}, delta: $delta}';
}
// coverage:ignore-start
final _finalizer = Finalizer<Pointer<git_patch>>(
(pointer) => bindings.free(pointer),
);
// coverage:ignore-end
/// Line counts of each type in a patch.
class PatchStats {
const PatchStats({
const PatchStats._({
required this.context,
required this.insertions,
required this.deletions,
@ -246,3 +287,83 @@ class PatchStats {
'deletions: $deletions}';
}
}
class DiffHunk {
const DiffHunk._({
required this.linesCount,
required this.index,
required this.oldStart,
required this.oldLines,
required this.newStart,
required this.newLines,
required this.header,
required this.lines,
});
/// Number of total lines in this hunk.
final int linesCount;
/// Index of this hunk in the patch.
final int index;
/// Starting line number in 'old file'.
final int oldStart;
/// Number of lines in 'old file'.
final int oldLines;
/// Starting line number in 'new file'.
final int newStart;
/// Number of lines in 'new file'.
final int newLines;
/// Header of a hunk.
final String header;
/// List of lines in a hunk of a patch.
final List<DiffLine> lines;
@override
String toString() {
return 'DiffHunk{linesCount: $linesCount, index: $index, '
'oldStart: $oldStart, oldLines: $oldLines, newStart: $newStart, '
'newLines: $newLines, header: $header}';
}
}
class DiffLine {
const DiffLine._({
required this.origin,
required this.oldLineNumber,
required this.newLineNumber,
required this.numLines,
required this.contentOffset,
required this.content,
});
/// Type of the line.
final GitDiffLine origin;
/// Line number in old file or -1 for added line.
final int oldLineNumber;
/// Line number in new file or -1 for deleted line.
final int newLineNumber;
/// Number of newline characters in content.
final int numLines;
/// Offset in the original file to the content.
final int contentOffset;
/// Content of the diff line.
final String content;
@override
String toString() {
return 'DiffLine{oldLineNumber: $oldLineNumber, '
'newLineNumber: $newLineNumber, numLines: $numLines, '
'contentOffset: $contentOffset, content: $content}';
}
}

View file

@ -17,8 +17,6 @@ class Rebase {
/// [onto] is the branch to rebase onto, default is to rebase onto the given
/// [upstream].
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Rebase.init({
required Repository repo,
@ -32,16 +30,16 @@ class Rebase {
upstreamPointer: upstream?.pointer,
ontoPointer: onto?.pointer,
);
_finalizer.attach(this, _rebasePointer, detach: this);
}
/// Opens an existing rebase that was previously started by either an
/// invocation of [Rebase.init] or by another client.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Rebase.open(Repository repo) {
_rebasePointer = bindings.open(repo.pointer);
_finalizer.attach(this, _rebasePointer, detach: this);
}
/// Pointer to memory address for allocated rebase object.
@ -57,7 +55,7 @@ class Rebase {
rebase: _rebasePointer,
index: i,
);
result.add(RebaseOperation(operation));
result.add(RebaseOperation._(operation));
}
return result;
@ -101,7 +99,7 @@ class Rebase {
///
/// Throws a [LibGit2Error] if error occured.
RebaseOperation next() {
return RebaseOperation(bindings.next(_rebasePointer));
return RebaseOperation._(bindings.next(_rebasePointer));
}
/// Commits the current patch. You must have resolved any conflicts that were
@ -138,13 +136,22 @@ class Rebase {
void abort() => bindings.abort(_rebasePointer);
/// Releases memory allocated for rebase object.
void free() => bindings.free(_rebasePointer);
void free() {
bindings.free(_rebasePointer);
_finalizer.detach(this);
}
}
// coverage:ignore-start
final _finalizer = Finalizer<Pointer<git_rebase>>(
(pointer) => bindings.free(pointer),
);
// coverage:ignore-end
class RebaseOperation {
/// Initializes a new instance of the [RebaseOperation] class from
/// provided pointer to rebase operation object in memory.
const RebaseOperation(this._rebaseOperationPointer);
const RebaseOperation._(this._rebaseOperationPointer);
/// Pointer to memory address for allocated rebase operation object.
final Pointer<git_rebase_operation> _rebaseOperationPointer;

View file

@ -10,17 +10,14 @@ import 'package:libgit2dart/src/bindings/repository.dart'
class Reference {
/// Initializes a new instance of the [Reference] class.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Reference(this._refPointer);
Reference(this._refPointer) {
_finalizer.attach(this, _refPointer, detach: this);
}
/// Creates a new reference for provided [target].
///
/// The reference will be created in the [repo]sitory and written to the disk.
///
/// **IMPORTANT**: The generated [Reference] object should be freed to release
/// allocated memory.
///
/// Valid reference [name]s must follow one of two patterns:
/// - Top-level names must contain only capital letters and underscores, and
/// must begin and end with a letter. (e.g. "HEAD", "ORIG_HEAD").
@ -65,17 +62,17 @@ class Reference {
'$target must be either Oid or String reference name',
);
}
_finalizer.attach(this, _refPointer, detach: this);
}
/// Lookups reference [name] in a [repo]sitory.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// The [name] will be checked for validity.
///
/// Throws a [LibGit2Error] if error occured.
Reference.lookup({required Repository repo, required String name}) {
_refPointer = bindings.lookup(repoPointer: repo.pointer, name: name);
_finalizer.attach(this, _refPointer, detach: this);
}
late Pointer<git_reference> _refPointer;
@ -89,7 +86,6 @@ class Reference {
static void delete({required Repository repo, required String name}) {
final ref = Reference.lookup(repo: repo, name: name);
bindings.delete(ref.pointer);
ref.free();
}
/// Renames an existing reference with provided [oldName].
@ -120,7 +116,6 @@ class Reference {
force: force,
logMessage: logMessage,
);
ref.free();
}
/// List of all the references names that can be found in a [repo]sitory.
@ -153,8 +148,6 @@ class Reference {
}
/// Creates a copy of an existing reference.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Reference duplicate() => Reference(bindings.duplicate(_refPointer));
/// Type of the reference.
@ -192,7 +185,6 @@ class Reference {
oidPointer: target.pointer,
logMessage: logMessage,
);
free();
_refPointer = newPointer;
} else if (target is String) {
final newPointer = bindings.setTargetSymbolic(
@ -200,7 +192,6 @@ class Reference {
target: target,
logMessage: logMessage,
);
free();
_refPointer = newPointer;
} else {
throw ArgumentError.value(
@ -261,8 +252,6 @@ class Reference {
}
/// [RefLog] object.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
RefLog get log => RefLog(this);
/// Whether reference is a local branch.
@ -292,7 +281,10 @@ class Reference {
bool notEquals(Reference other) => !equals(other);
/// Releases memory allocated for reference object.
void free() => bindings.free(_refPointer);
void free() {
bindings.free(_refPointer);
_finalizer.detach(this);
}
@override
String toString() {
@ -301,3 +293,9 @@ class Reference {
'isTag: $isTag}';
}
}
// coverage:ignore-start
final _finalizer = Finalizer<Pointer<git_reference>>(
(pointer) => bindings.free(pointer),
);
// coverage:ignore-end

View file

@ -6,13 +6,12 @@ import 'package:libgit2dart/src/bindings/reflog.dart' as bindings;
class RefLog with IterableMixin<RefLogEntry> {
/// Initializes a new instance of [RefLog] class from provided [Reference].
///
/// **IMPORTANT**: Should be freed to release allocated memory.
RefLog(Reference ref) {
_reflogPointer = bindings.read(
repoPointer: ref.owner.pointer,
name: ref.name,
);
_finalizer.attach(this, _reflogPointer, detach: this);
}
/// Pointer to memory address for allocated reflog object.
@ -47,7 +46,7 @@ class RefLog with IterableMixin<RefLogEntry> {
/// Requesting the reflog entry with an index of 0 will return the most
/// recently created entry.
RefLogEntry operator [](int index) {
return RefLogEntry(
return RefLogEntry._(
bindings.getByIndex(
reflogPointer: _reflogPointer,
index: index,
@ -89,16 +88,25 @@ class RefLog with IterableMixin<RefLogEntry> {
void write() => bindings.write(_reflogPointer);
/// Releases memory allocated for reflog object.
void free() => bindings.free(_reflogPointer);
void free() {
bindings.free(_reflogPointer);
_finalizer.detach(this);
}
@override
Iterator<RefLogEntry> get iterator => _RefLogIterator(_reflogPointer);
}
// coverage:ignore-start
final _finalizer = Finalizer<Pointer<git_reflog>>(
(pointer) => bindings.free(pointer),
);
// coverage:ignore-end
class RefLogEntry {
/// Initializes a new instance of [RefLogEntry] class from provided
/// pointer to RefLogEntry object in memory.
const RefLogEntry(this._entryPointer);
const RefLogEntry._(this._entryPointer);
/// Pointer to memory address for allocated reflog entry object.
final Pointer<git_reflog_entry> _entryPointer;
@ -141,7 +149,7 @@ class _RefLogIterator implements Iterator<RefLogEntry> {
if (_index == _count) {
return false;
} else {
_currentEntry = RefLogEntry(
_currentEntry = RefLogEntry._(
bindings.getByIndex(
reflogPointer: _reflogPointer,
index: _index,

View file

@ -8,18 +8,15 @@ class Remote {
///
/// The [name] will be checked for validity.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Remote.lookup({required Repository repo, required String name}) {
_remotePointer = bindings.lookup(repoPointer: repo.pointer, name: name);
_finalizer.attach(this, _remotePointer, detach: this);
}
/// Adds remote with provided [name] and [url] to the [repo]sitory's
/// configuration with the default [fetch] refspec if none provided.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Remote.create({
required Repository repo,
@ -41,12 +38,11 @@ class Remote {
fetch: fetch,
);
}
_finalizer.attach(this, _remotePointer, detach: this);
}
late final Pointer<git_remote> _remotePointer;
/// Pointer to memory address for allocated remote object.
Pointer<git_remote> get pointer => _remotePointer;
late final Pointer<git_remote> _remotePointer;
/// Deletes an existing persisted remote with provided [name].
///
@ -298,7 +294,10 @@ class Remote {
}
/// Releases memory allocated for remote object.
void free() => bindings.free(_remotePointer);
void free() {
bindings.free(_remotePointer);
_finalizer.detach(this);
}
@override
String toString() {
@ -307,6 +306,12 @@ class Remote {
}
}
// coverage:ignore-start
final _finalizer = Finalizer<Pointer<git_remote>>(
(pointer) => bindings.free(pointer),
);
// coverage:ignore-end
/// Provides callers information about the progress of indexing a packfile,
/// either directly or part of a fetch or clone that downloads a packfile.
class TransferProgress {
@ -346,3 +351,21 @@ class TransferProgress {
'indexedDeltas: $indexedDeltas, receivedBytes: $receivedBytes}';
}
}
class RemoteCallback {
/// Values used to override the remote creation and customization process
/// during a repository clone operation.
///
/// Remote will have provided [name] and [url] with the default [fetch]
/// refspec if none provided.
const RemoteCallback({required this.name, required this.url, this.fetch});
/// Remote's name.
final String name;
/// Remote's url.
final String url;
/// Remote's fetch refspec.
final String? fetch;
}

View file

@ -111,13 +111,11 @@ class Repository {
///
/// [bare] whether cloned repo should be bare.
///
/// [remote] is the callback function with
/// `Remote Function(Repository repo, String name, String url)` signature.
/// The [Remote] it returns will be used instead of default one.
/// [remoteCallback] is the [RemoteCallback] object values that will be used
/// in creation and customization process of remote instead of default ones.
///
/// [repository] is the callback function matching the
/// `Repository Function(String path, bool bare)` signature. The [Repository]
/// it returns will be used instead of creating a new one.
/// [repositoryCallback] is the [RepositoryCallback] object values that will
/// be used in creation and customization process of repository.
///
/// [checkoutBranch] is the name of the branch to checkout after the clone.
/// Defaults to using the remote's default branch.
@ -132,8 +130,8 @@ class Repository {
required String url,
required String localPath,
bool bare = false,
Remote Function(Repository, String, String)? remote,
Repository Function(String, bool)? repository,
RemoteCallback? remoteCallback,
RepositoryCallback? repositoryCallback,
String? checkoutBranch,
Callbacks callbacks = const Callbacks(),
}) {
@ -143,8 +141,8 @@ class Repository {
url: url,
localPath: localPath,
bare: bare,
remote: remote,
repository: repository,
remoteCallback: remoteCallback,
repositoryCallback: repositoryCallback,
checkoutBranch: checkoutBranch,
callbacks: callbacks,
);
@ -375,8 +373,6 @@ class Repository {
/// If a configuration file has not been set, the default config set for the
/// repository will be returned, including global and system configurations
/// (if they are available).
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Config get config => Config(bindings.config(_repoPointer));
/// Snapshot of the repository's configuration.
@ -386,24 +382,16 @@ class Repository {
///
/// The contents of this snapshot will not change, even if the underlying
/// config files are modified.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Config get configSnapshot => Config(bindings.configSnapshot(_repoPointer));
/// Repository's head.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Reference get head => Reference(bindings.head(_repoPointer));
/// Index file for this repository.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Index get index => Index(bindings.index(_repoPointer));
/// ODB for this repository.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Odb get odb => Odb(bindings.odb(_repoPointer));
@ -419,23 +407,17 @@ class Repository {
/// List of all branches that can be found in a repository.
///
/// **IMPORTANT**: Branches should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
List<Branch> get branches => Branch.list(repo: this);
/// List of local branches that can be found in a repository.
///
/// **IMPORTANT**: Branches should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
List<Branch> get branchesLocal =>
Branch.list(repo: this, type: GitBranch.local);
/// List of remote branches that can be found in a repository.
///
/// **IMPORTANT**: Branches should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
List<Branch> get branchesRemote =>
Branch.list(repo: this, type: GitBranch.remote);
@ -465,8 +447,6 @@ class Repository {
///
/// If [sorting] isn't provided default will be used (reverse chronological
/// order, like in git).
///
/// **IMPORTANT**: Commits should be freed to release allocated memory.
List<Commit> log({
required Oid oid,
Set<GitSort> sorting = const {GitSort.none},
@ -477,8 +457,6 @@ class Repository {
walker.push(oid);
final result = walker.walk();
walker.free();
return result;
}
@ -737,6 +715,7 @@ class Repository {
}
}
// ignore: no_leading_underscores_for_local_identifiers
final _packDelegate = packDelegate ?? packAll;
final packbuilder = PackBuilder(this);
@ -745,10 +724,79 @@ class Repository {
}
_packDelegate(packbuilder);
packbuilder.write(path);
final result = packbuilder.writtenLength;
packbuilder.free();
return result;
return packbuilder.writtenLength;
}
}
class RepositoryCallback {
/// Values used to override the repository creation and customization process
/// during a clone operation.
///
/// [path] is the path to the repository.
///
/// [bare] whether new repository should be bare.
///
/// [flags] is a combination of [GitRepositoryInit] flags. Defaults to
/// [GitRepositoryInit.mkdir].
///
/// [mode] is the permissions for the folder. Default to 0 (permissions
/// configured by umask).
///
/// [workdirPath] is the path to the working directory. Can be null for
/// default path.
///
/// [description] if set will be used to initialize the "description" file in
/// the repository, instead of using the template content.
///
/// [templatePath] is the the path to use for the template directory if
/// [GitRepositoryInit.externalTemplate] is set. Defaults to the config or
/// default directory options.
///
/// [initialHead] is the name of the head to point HEAD at. If null, then
/// this will be treated as "master" and the HEAD ref will be set to
/// "refs/heads/master". If this begins with "refs/" it will be used
/// verbatim, otherwise "refs/heads/" will be prefixed.
///
/// [originUrl] if set, then after the rest of the repository initialization
/// is completed, an "origin" remote will be added pointing to this URL.
const RepositoryCallback({
required this.path,
this.bare = false,
this.flags = const {GitRepositoryInit.mkpath},
this.mode = 0,
this.workdirPath,
this.description,
this.templatePath,
this.initialHead,
this.originUrl,
});
/// Path to the repository.
final String path;
/// Whether repository is bare.
final bool bare;
/// Combination of [GitRepositoryInit] flags.
final Set<GitRepositoryInit> flags;
/// Permissions for the repository folder.
final int mode;
/// Path to the working directory.
final String? workdirPath;
/// Description used to initialize the "description" file in the repository.
final String? description;
/// Path used for the template directory.
final String? templatePath;
/// Name of the head HEAD points at.
final String? initialHead;
/// "origin" remote URL that will be added after the rest of the repository
/// initialization is completed.
final String? originUrl;
}

View file

@ -15,8 +15,6 @@ class RevParse {
/// point to an intermediate reference. When such expressions are being
/// passed in, reference_out will be valued as well.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
RevParse.ext({required Repository repo, required String spec}) {
final pointers = bindings.revParseExt(
@ -51,8 +49,6 @@ class RevParse {
/// final tag = RevParse.single(repo: repo, spec: 'v1.0') as Tag;
/// ```
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
static Object single({required Repository repo, required String spec}) {
final object = bindings.revParseSingle(
@ -79,7 +75,7 @@ class RevParse {
///
/// Throws a [LibGit2Error] if error occured.
static RevSpec range({required Repository repo, required String spec}) {
return RevSpec(
return RevSpec._(
bindings.revParse(
repoPointer: repo.pointer,
spec: spec,
@ -96,19 +92,15 @@ class RevParse {
class RevSpec {
/// Initializes a new instance of [RevSpec] class from provided
/// pointer to revspec object in memory.
const RevSpec(this._revSpecPointer);
const RevSpec._(this._revSpecPointer);
/// Pointer to memory address for allocated revspec object.
final Pointer<git_revspec> _revSpecPointer;
/// Left element of the revspec.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Commit get from => Commit(_revSpecPointer.ref.from.cast());
/// Right element of the revspec.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Commit? get to {
return _revSpecPointer.ref.to == nullptr
? null

View file

@ -5,10 +5,9 @@ import 'package:libgit2dart/src/bindings/revwalk.dart' as bindings;
class RevWalk {
/// Initializes a new instance of the [RevWalk] class.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
RevWalk(Repository repo) {
_revWalkPointer = bindings.create(repo.pointer);
_finalizer.attach(this, _revWalkPointer, detach: this);
}
late final Pointer<git_revwalk> _revWalkPointer;
@ -150,5 +149,14 @@ class RevWalk {
void simplifyFirstParent() => bindings.simplifyFirstParent(_revWalkPointer);
/// Releases memory allocated for [RevWalk] object.
void free() => bindings.free(_revWalkPointer);
void free() {
bindings.free(_revWalkPointer);
_finalizer.detach(this);
}
}
// coverage:ignore-start
final _finalizer = Finalizer<Pointer<git_revwalk>>(
(pointer) => bindings.free(pointer),
);
// coverage:ignore-end

View file

@ -10,17 +10,16 @@ import 'package:meta/meta.dart';
class Signature {
/// Initializes a new instance of [Signature] class from provided pointer to
/// signature object in memory.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Signature(this._signaturePointer);
Signature(Pointer<git_signature> pointer) {
_signaturePointer = bindings.duplicate(pointer);
_finalizer.attach(this, _signaturePointer, detach: this);
}
/// Creates new [Signature] from provided [name], [email], and optional [time]
/// in seconds from epoch and [offset] in minutes.
///
/// If [time] isn't provided [Signature] will be created with a timestamp of
/// 'now'.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Signature.create({
required String name,
required String email,
@ -39,6 +38,7 @@ class Signature {
offset: offset,
);
}
_finalizer.attach(this, _signaturePointer, detach: this);
}
/// Creates a new action signature with default user and now timestamp.
@ -48,6 +48,7 @@ class Signature {
/// on that information.
Signature.defaultSignature(Repository repo) {
_signaturePointer = bindings.defaultSignature(repo.pointer);
_finalizer.attach(this, _signaturePointer, detach: this);
}
late final Pointer<git_signature> _signaturePointer;
@ -79,7 +80,10 @@ class Signature {
}
/// Releases memory allocated for signature object.
void free() => bindings.free(_signaturePointer);
void free() {
bindings.free(_signaturePointer);
_finalizer.detach(this);
}
@override // coverage:ignore-line
int get hashCode =>
@ -91,3 +95,9 @@ class Signature {
'offset: $offset}';
}
}
// coverage:ignore-start
final _finalizer = Finalizer<Pointer<git_signature>>(
(pointer) => bindings.free(pointer),
);
// coverage:ignore-end

View file

@ -7,14 +7,13 @@ class Submodule {
/// Lookups submodule information by [name] or path (they are usually the
/// same).
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Submodule.lookup({required Repository repo, required String name}) {
_submodulePointer = bindings.lookup(
repoPointer: repo.pointer,
name: name,
);
_finalizer.attach(this, _submodulePointer, detach: this);
}
/// Adds a submodule to the index.
@ -29,8 +28,6 @@ class Submodule {
/// [callbacks] is the combination of callback functions from [Callbacks]
/// object.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Submodule.add({
required Repository repo,
@ -49,6 +46,8 @@ class Submodule {
bindings.clone(submodule: _submodulePointer, callbacks: callbacks);
bindings.addFinalize(_submodulePointer);
_finalizer.attach(this, _submodulePointer, detach: this);
}
/// Pointer to memory address for allocated submodule object.
@ -264,7 +263,10 @@ class Submodule {
}
/// Releases memory allocated for submodule object.
void free() => bindings.free(_submodulePointer);
void free() {
bindings.free(_submodulePointer);
_finalizer.detach(this);
}
@override
String toString() {
@ -273,3 +275,9 @@ class Submodule {
'workdirOid: $workdirOid, ignore: $ignore, updateRule: $updateRule}';
}
}
// coverage:ignore-start
final _finalizer = Finalizer<Pointer<git_submodule>>(
(pointer) => bindings.free(pointer),
);
// coverage:ignore-end

View file

@ -8,18 +8,17 @@ import 'package:libgit2dart/src/bindings/tag.dart' as bindings;
class Tag {
/// Initializes a new instance of [Tag] class from provided pointer to
/// tag object in memory.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Tag(this._tagPointer);
Tag(this._tagPointer) {
_finalizer.attach(this, _tagPointer, detach: this);
}
/// Lookups tag object for provided [oid] in a [repo]sitory.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Tag.lookup({required Repository repo, required Oid oid}) {
_tagPointer = bindings.lookup(
repoPointer: repo.pointer,
oidPointer: oid.pointer,
);
_finalizer.attach(this, _tagPointer, detach: this);
}
/// Pointer to memory address for allocated tag object.
@ -160,9 +159,6 @@ class Tag {
/// Returned object should be explicitly downcasted to one of four of git
/// object types.
///
/// **IMPORTANT**: returned object should be freed to release allocated
/// memory.
///
/// ```dart
/// final commit = tag.target as Commit;
/// final tree = tag.target as Tree;
@ -215,7 +211,10 @@ class Tag {
}
/// Releases memory allocated for tag object.
void free() => bindings.free(_tagPointer);
void free() {
bindings.free(_tagPointer);
_finalizer.detach(this);
}
@override
String toString() {
@ -223,3 +222,9 @@ class Tag {
'tagger: $tagger}';
}
}
// coverage:ignore-start
final _finalizer = Finalizer<Pointer<git_tag>>(
(pointer) => bindings.free(pointer),
);
// coverage:ignore-end

View file

@ -7,18 +7,17 @@ import 'package:libgit2dart/src/bindings/tree.dart' as bindings;
class Tree {
/// Initializes a new instance of [Tree] class from provided pointer to
/// tree object in memory.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Tree(this._treePointer);
Tree(this._treePointer) {
_finalizer.attach(this, _treePointer, detach: this);
}
/// Lookups a tree object for provided [oid] in a [repo]sitory.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
Tree.lookup({required Repository repo, required Oid oid}) {
_treePointer = bindings.lookup(
repoPointer: repo.pointer,
oidPointer: oid.pointer,
);
_finalizer.attach(this, _treePointer, detach: this);
}
late final Pointer<git_tree> _treePointer;
@ -63,7 +62,7 @@ class Tree {
),
);
} else if (value is String && value.contains('/')) {
return TreeEntry(
return TreeEntry._byPath(
bindings.getByPath(
rootPointer: _treePointer,
path: value,
@ -90,7 +89,10 @@ class Tree {
int get length => bindings.entryCount(_treePointer);
/// Releases memory allocated for tree object.
void free() => bindings.free(_treePointer);
void free() {
bindings.free(_treePointer);
_finalizer.detach(this);
}
@override
String toString() {
@ -98,10 +100,24 @@ class Tree {
}
}
// coverage:ignore-start
final _finalizer = Finalizer<Pointer<git_tree>>(
(pointer) => bindings.free(pointer),
);
// coverage:ignore-end
class TreeEntry {
/// Initializes a new instance of [TreeEntry] class from provided pointer to
/// tree entry object in memory.
const TreeEntry(this._treeEntryPointer);
TreeEntry(this._treeEntryPointer);
/// Initializes a new instance of [TreeEntry] class from provided pointer to
/// tree entry object in memory.
///
/// Unlike the other lookup methods, must be freed.
TreeEntry._byPath(this._treeEntryPointer) {
_entryFinalizer.attach(this, _treeEntryPointer, detach: this);
}
/// Pointer to memory address for allocated tree entry object.
final Pointer<git_tree_entry> _treeEntryPointer;
@ -119,8 +135,19 @@ class TreeEntry {
}
/// Releases memory allocated for tree entry object.
void free() => bindings.entryFree(_treeEntryPointer);
///
/// **IMPORTANT**: Only tree entries looked up by path should be freed.
void free() {
bindings.entryFree(_treeEntryPointer);
_entryFinalizer.detach(this);
}
@override
String toString() => 'TreeEntry{oid: $oid, name: $name, filemode: $filemode}';
}
// coverage:ignore-start
final _entryFinalizer = Finalizer<Pointer<git_tree_entry>>(
(pointer) => bindings.entryFree(pointer),
);
// coverage:ignore-end

View file

@ -7,14 +7,13 @@ class TreeBuilder {
/// Initializes a new instance of [TreeBuilder] class from provided
/// [repo]sitory and optional [tree] objects.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
TreeBuilder({required Repository repo, Tree? tree}) {
_treeBuilderPointer = bindings.create(
repoPointer: repo.pointer,
sourcePointer: tree?.pointer ?? nullptr,
);
_finalizer.attach(this, _treeBuilderPointer, detach: this);
}
/// Pointer to memory address for allocated tree builder object.
@ -31,9 +30,6 @@ class TreeBuilder {
/// Returns an entry from the tree builder with provided [filename].
///
/// **IMPORTANT**: the returned entry is owned by the tree builder and
/// should not be freed manually.
///
/// Throws [ArgumentError] if nothing found for provided [filename].
TreeEntry operator [](String filename) {
return TreeEntry(
@ -83,10 +79,19 @@ class TreeBuilder {
}
/// Releases memory allocated for tree builder object and all the entries.
void free() => bindings.free(_treeBuilderPointer);
void free() {
bindings.free(_treeBuilderPointer);
_finalizer.detach(this);
}
@override
String toString() {
return 'TreeBuilder{length: $length}';
}
}
// coverage:ignore-start
final _finalizer = Finalizer<Pointer<git_treebuilder>>(
(pointer) => bindings.free(pointer),
);
// coverage:ignore-end

View file

@ -15,8 +15,6 @@ class Worktree {
///
/// [path] is the path to create working tree at.
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Worktree.create({
required Repository repo,
@ -30,15 +28,15 @@ class Worktree {
path: path,
refPointer: ref?.pointer,
);
_finalizer.attach(this, _worktreePointer, detach: this);
}
/// Lookups existing worktree in [repo] with provided [name].
///
/// **IMPORTANT**: Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Worktree.lookup({required Repository repo, required String name}) {
_worktreePointer = bindings.lookup(repoPointer: repo.pointer, name: name);
_finalizer.attach(this, _worktreePointer, detach: this);
}
/// Pointer to memory address for allocated branch object.
@ -88,10 +86,19 @@ class Worktree {
bool get isValid => bindings.isValid(_worktreePointer);
/// Releases memory allocated for worktree object.
void free() => bindings.free(_worktreePointer);
void free() {
bindings.free(_worktreePointer);
_finalizer.detach(this);
}
@override
String toString() {
return 'Worktree{name: $name, path: $path}';
}
}
// coverage:ignore-start
final _finalizer = Finalizer<Pointer<git_worktree>>(
(pointer) => bindings.free(pointer),
);
// coverage:ignore-end