test: add more tests for throws and their messages

This commit is contained in:
Aleksey Kulikov 2021-10-19 17:16:39 +03:00
parent d6eae1e9ed
commit 127849519d
80 changed files with 2741 additions and 1501 deletions

View file

@ -1,6 +1,5 @@
import 'dart:ffi'; import 'dart:ffi';
import 'package:ffi/ffi.dart'; import 'package:ffi/ffi.dart';
import '../error.dart';
import '../util.dart'; import '../util.dart';
import 'libgit2_bindings.dart'; import 'libgit2_bindings.dart';
@ -8,8 +7,6 @@ import 'libgit2_bindings.dart';
/// ///
/// Returned value can be either `true`, `false`, `null` (if the attribute was not set at all), /// Returned value can be either `true`, `false`, `null` (if the attribute was not set at all),
/// or a [String] value, if the attribute was set to an actual string. /// or a [String] value, if the attribute was set to an actual string.
///
/// Throws a [LibGit2Error] if error occured.
Object? getAttribute({ Object? getAttribute({
required Pointer<git_repository> repoPointer, required Pointer<git_repository> repoPointer,
required int flags, required int flags,
@ -19,33 +16,28 @@ Object? getAttribute({
final out = calloc<Pointer<Int8>>(); final out = calloc<Pointer<Int8>>();
final pathC = path.toNativeUtf8().cast<Int8>(); final pathC = path.toNativeUtf8().cast<Int8>();
final nameC = name.toNativeUtf8().cast<Int8>(); final nameC = name.toNativeUtf8().cast<Int8>();
final error = libgit2.git_attr_get(out, repoPointer, flags, pathC, nameC); libgit2.git_attr_get(out, repoPointer, flags, pathC, nameC);
calloc.free(pathC); calloc.free(pathC);
calloc.free(nameC); calloc.free(nameC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
}
final attributeValue = libgit2.git_attr_value(out.value); final attributeValue = libgit2.git_attr_value(out.value);
if (attributeValue == git_attr_value_t.GIT_ATTR_VALUE_UNSPECIFIED) { if (attributeValue == git_attr_value_t.GIT_ATTR_VALUE_UNSPECIFIED) {
calloc.free(out); calloc.free(out);
return null; return null;
} else if (attributeValue == git_attr_value_t.GIT_ATTR_VALUE_TRUE) { }
if (attributeValue == git_attr_value_t.GIT_ATTR_VALUE_TRUE) {
calloc.free(out); calloc.free(out);
return true; return true;
} else if (attributeValue == git_attr_value_t.GIT_ATTR_VALUE_FALSE) { }
if (attributeValue == git_attr_value_t.GIT_ATTR_VALUE_FALSE) {
calloc.free(out); calloc.free(out);
return false; return false;
} else if (attributeValue == git_attr_value_t.GIT_ATTR_VALUE_STRING) { }
if (attributeValue == git_attr_value_t.GIT_ATTR_VALUE_STRING) {
final result = out.value.cast<Utf8>().toDartString(); final result = out.value.cast<Utf8>().toDartString();
calloc.free(out); calloc.free(out);
return result; return result;
} else {
calloc.free(out);
throw Exception('The attribute value from libgit2 is invalid');
} }
} }

View file

@ -21,17 +21,7 @@ Pointer<git_blame> file({
final out = calloc<Pointer<git_blame>>(); final out = calloc<Pointer<git_blame>>();
final pathC = path.toNativeUtf8().cast<Int8>(); final pathC = path.toNativeUtf8().cast<Int8>();
final options = calloc<git_blame_options>(); final options = calloc<git_blame_options>();
final optionsError = libgit2.git_blame_options_init( libgit2.git_blame_options_init(options, GIT_BLAME_OPTIONS_VERSION);
options,
GIT_BLAME_OPTIONS_VERSION,
);
if (optionsError < 0) {
calloc.free(out);
calloc.free(pathC);
calloc.free(options);
throw LibGit2Error(libgit2.git_error_last());
}
options.ref.flags = flags; options.ref.flags = flags;

View file

@ -24,32 +24,8 @@ Pointer<git_commit> lookup({
} }
} }
/// Lookup a commit object from a repository, given a prefix of its identifier (short id). /// Creates an annotated commit from the given commit id. The resulting annotated commit
/// /// must be freed with [annotatedFree].
/// Throws a [LibGit2Error] if error occured.
Pointer<git_commit> lookupPrefix({
required Pointer<git_repository> repoPointer,
required Pointer<git_oid> oidPointer,
required int len,
}) {
final out = calloc<Pointer<git_commit>>();
final error = libgit2.git_commit_lookup_prefix(
out,
repoPointer,
oidPointer,
len,
);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
}
}
/// Creates a git_annotated_commit from the given commit id. The resulting git_annotated_commit
/// must be freed with git_annotated_commit_free.
/// ///
/// An annotated commit contains information about how it was looked up, which may be useful /// An annotated commit contains information about how it was looked up, which may be useful
/// for functions like merge or rebase to provide context to the operation. For example, conflict /// for functions like merge or rebase to provide context to the operation. For example, conflict
@ -77,7 +53,7 @@ Pointer<Pointer<git_annotated_commit>> annotatedLookup({
} }
} }
/// Frees a git_annotated_commit. /// Frees an annotated commit.
void annotatedFree(Pointer<git_annotated_commit> commit) { void annotatedFree(Pointer<git_annotated_commit> commit) {
libgit2.git_annotated_commit_free(commit); libgit2.git_annotated_commit_free(commit);
} }
@ -168,13 +144,7 @@ Pointer<git_oid> parentId({
required Pointer<git_commit> commitPointer, required Pointer<git_commit> commitPointer,
required int position, required int position,
}) { }) {
final parentOid = libgit2.git_commit_parent_id(commitPointer, position); return libgit2.git_commit_parent_id(commitPointer, position);
if (parentOid == nullptr) {
throw LibGit2Error(libgit2.git_error_last());
} else {
return parentOid;
}
} }
/// Get the commit time (i.e. committer time) of a commit. /// Get the commit time (i.e. committer time) of a commit.
@ -209,15 +179,8 @@ Pointer<git_index> revertCommit({
}) { }) {
final out = calloc<Pointer<git_index>>(); final out = calloc<Pointer<git_index>>();
final opts = calloc<git_merge_options>(); final opts = calloc<git_merge_options>();
final optsError =
libgit2.git_merge_options_init(opts, GIT_MERGE_OPTIONS_VERSION); libgit2.git_merge_options_init(opts, GIT_MERGE_OPTIONS_VERSION);
if (optsError < 0) {
calloc.free(out);
calloc.free(opts);
throw LibGit2Error(libgit2.git_error_last());
}
final error = libgit2.git_revert_commit( final error = libgit2.git_revert_commit(
out, out,
repoPointer, repoPointer,

View file

@ -77,8 +77,6 @@ Pointer<git_describe_result> workdir({
} }
/// Print the describe result to a buffer. /// Print the describe result to a buffer.
///
/// Throws a [LibGit2Error] if error occured.
String format({ String format({
required Pointer<git_describe_result> describeResultPointer, required Pointer<git_describe_result> describeResultPointer,
int? abbreviatedSize, int? abbreviatedSize,
@ -87,17 +85,11 @@ String format({
}) { }) {
final out = calloc<git_buf>(sizeOf<git_buf>()); final out = calloc<git_buf>(sizeOf<git_buf>());
final opts = calloc<git_describe_format_options>(); final opts = calloc<git_describe_format_options>();
final optsError = libgit2.git_describe_format_options_init( libgit2.git_describe_format_options_init(
opts, opts,
GIT_DESCRIBE_FORMAT_OPTIONS_VERSION, GIT_DESCRIBE_FORMAT_OPTIONS_VERSION,
); );
if (optsError < 0) {
calloc.free(out);
calloc.free(opts);
throw LibGit2Error(libgit2.git_error_last());
}
if (abbreviatedSize != null) { if (abbreviatedSize != null) {
opts.ref.abbreviated_size = abbreviatedSize; opts.ref.abbreviated_size = abbreviatedSize;
} }
@ -108,19 +100,15 @@ String format({
opts.ref.dirty_suffix = dirtySuffix.toNativeUtf8().cast<Int8>(); opts.ref.dirty_suffix = dirtySuffix.toNativeUtf8().cast<Int8>();
} }
final error = libgit2.git_describe_format(out, describeResultPointer, opts); libgit2.git_describe_format(out, describeResultPointer, opts);
final result = out.ref.ptr.cast<Utf8>().toDartString();
calloc.free(opts); calloc.free(opts);
calloc.free(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
final result = out.ref.ptr.cast<Utf8>().toDartString();
calloc.free(out);
return result; return result;
} }
}
/// Free the describe result. /// Free the describe result.
void describeResultFree(Pointer<git_describe_result> result) { void describeResultFree(Pointer<git_describe_result> result) {
@ -136,15 +124,11 @@ Pointer<git_describe_options> _initOpts({
bool? showCommitOidAsFallback, bool? showCommitOidAsFallback,
}) { }) {
final opts = calloc<git_describe_options>(); final opts = calloc<git_describe_options>();
final error = libgit2.git_describe_options_init( libgit2.git_describe_options_init(
opts, opts,
GIT_DESCRIBE_OPTIONS_VERSION, GIT_DESCRIBE_OPTIONS_VERSION,
); );
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
if (maxCandidatesTags != null) { if (maxCandidatesTags != null) {
opts.ref.max_candidates_tags = maxCandidatesTags; opts.ref.max_candidates_tags = maxCandidatesTags;
} }

View file

@ -5,8 +5,6 @@ import 'libgit2_bindings.dart';
import '../util.dart'; import '../util.dart';
/// Create a diff between the repository index and the workdir directory. /// Create a diff between the repository index and the workdir directory.
///
/// Throws a [LibGit2Error] if error occured.
Pointer<git_diff> indexToWorkdir({ Pointer<git_diff> indexToWorkdir({
required Pointer<git_repository> repoPointer, required Pointer<git_repository> repoPointer,
required Pointer<git_index> indexPointer, required Pointer<git_index> indexPointer,
@ -21,16 +19,7 @@ Pointer<git_diff> indexToWorkdir({
interhunkLines: interhunkLines, interhunkLines: interhunkLines,
); );
final error = libgit2.git_diff_index_to_workdir( libgit2.git_diff_index_to_workdir(out, repoPointer, indexPointer, opts);
out,
repoPointer,
indexPointer,
opts,
);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
calloc.free(opts); calloc.free(opts);
@ -38,8 +27,6 @@ Pointer<git_diff> indexToWorkdir({
} }
/// Create a diff between a tree and repository index. /// Create a diff between a tree and repository index.
///
/// Throws a [LibGit2Error] if error occured.
Pointer<git_diff> treeToIndex({ Pointer<git_diff> treeToIndex({
required Pointer<git_repository> repoPointer, required Pointer<git_repository> repoPointer,
required Pointer<git_tree> treePointer, required Pointer<git_tree> treePointer,
@ -55,7 +42,7 @@ Pointer<git_diff> treeToIndex({
interhunkLines: interhunkLines, interhunkLines: interhunkLines,
); );
final error = libgit2.git_diff_tree_to_index( libgit2.git_diff_tree_to_index(
out, out,
repoPointer, repoPointer,
treePointer, treePointer,
@ -63,10 +50,6 @@ Pointer<git_diff> treeToIndex({
opts, opts,
); );
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
calloc.free(opts); calloc.free(opts);
return out.value; return out.value;
@ -166,22 +149,15 @@ void merge({
/// ///
/// This function will only read patch files created by a git implementation, it will not /// This function will only read patch files created by a git implementation, it will not
/// read unified diffs produced by the `diff` program, nor any other types of patch files. /// read unified diffs produced by the `diff` program, nor any other types of patch files.
///
/// Throws a [LibGit2Error] if error occured.
Pointer<git_diff> parse(String content) { Pointer<git_diff> parse(String content) {
final out = calloc<Pointer<git_diff>>(); final out = calloc<Pointer<git_diff>>();
final contentC = content.toNativeUtf8().cast<Int8>(); final contentC = content.toNativeUtf8().cast<Int8>();
final error = libgit2.git_diff_from_buffer(out, contentC, content.length); libgit2.git_diff_from_buffer(out, contentC, content.length);
calloc.free(contentC); calloc.free(contentC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value; return out.value;
} }
}
/// Transform a diff marking file renames, copies, etc. /// Transform a diff marking file renames, copies, etc.
/// ///
@ -200,15 +176,7 @@ void findSimilar({
required int renameLimit, required int renameLimit,
}) { }) {
final opts = calloc<git_diff_find_options>(); final opts = calloc<git_diff_find_options>();
final optsError = libgit2.git_diff_find_options_init( libgit2.git_diff_find_options_init(opts, GIT_DIFF_FIND_OPTIONS_VERSION);
opts,
GIT_DIFF_FIND_OPTIONS_VERSION,
);
if (optsError < 0) {
calloc.free(opts);
throw LibGit2Error(libgit2.git_error_last());
}
opts.ref.flags = flags; opts.ref.flags = flags;
opts.ref.rename_threshold = renameThreshold; opts.ref.rename_threshold = renameThreshold;
@ -236,7 +204,7 @@ void findSimilar({
/// and should in fact generate the same IDs as the upstream git project does. /// and should in fact generate the same IDs as the upstream git project does.
/// ///
/// Throws a [LibGit2Error] if error occured. /// Throws a [LibGit2Error] if error occured.
Pointer<git_oid> patchId(Pointer<git_diff> diff) { Pointer<git_oid> patchOid(Pointer<git_diff> diff) {
final out = calloc<git_oid>(); final out = calloc<git_oid>();
final error = libgit2.git_diff_patchid(out, diff, nullptr); final error = libgit2.git_diff_patchid(out, diff, nullptr);
@ -249,19 +217,11 @@ Pointer<git_oid> patchId(Pointer<git_diff> diff) {
} }
/// Return the diff delta for an entry in the diff list. /// Return the diff delta for an entry in the diff list.
///
/// Throws [RangeError] if index out of range.
Pointer<git_diff_delta> getDeltaByIndex({ Pointer<git_diff_delta> getDeltaByIndex({
required Pointer<git_diff> diffPointer, required Pointer<git_diff> diffPointer,
required int index, required int index,
}) { }) {
final result = libgit2.git_diff_get_delta(diffPointer, index); return libgit2.git_diff_get_delta(diffPointer, index);
if (result == nullptr) {
throw RangeError('$index is out of bounds');
} else {
return result;
}
} }
/// Look up the single character abbreviation for a delta status code. /// Look up the single character abbreviation for a delta status code.
@ -323,20 +283,14 @@ String statsPrint({
} }
/// Add patch to buffer. /// Add patch to buffer.
///
/// Throws a [LibGit2Error] if error occured.
Pointer<git_buf> addToBuf({ Pointer<git_buf> addToBuf({
required Pointer<git_patch> patchPointer, required Pointer<git_patch> patchPointer,
required Pointer<git_buf> bufferPointer, required Pointer<git_buf> bufferPointer,
}) { }) {
final error = libgit2.git_patch_to_buf(bufferPointer, patchPointer); libgit2.git_patch_to_buf(bufferPointer, patchPointer);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
} else {
return bufferPointer; return bufferPointer;
} }
}
/// Apply a diff to the given repository, making changes directly in the working directory, /// Apply a diff to the given repository, making changes directly in the working directory,
/// the index, or both. /// the index, or both.
@ -351,7 +305,7 @@ bool apply({
final opts = calloc<git_apply_options>(); final opts = calloc<git_apply_options>();
libgit2.git_apply_options_init(opts, GIT_APPLY_OPTIONS_VERSION); libgit2.git_apply_options_init(opts, GIT_APPLY_OPTIONS_VERSION);
if (check) { if (check) {
opts.ref.flags = git_apply_flags_t.GIT_APPLY_CHECK; opts.ref.flags |= git_apply_flags_t.GIT_APPLY_CHECK;
} }
final error = libgit2.git_apply(repoPointer, diffPointer, location, opts); final error = libgit2.git_apply(repoPointer, diffPointer, location, opts);
@ -377,18 +331,10 @@ Pointer<git_diff_options> _diffOptionsInit({
required int interhunkLines, required int interhunkLines,
}) { }) {
final opts = calloc<git_diff_options>(); final opts = calloc<git_diff_options>();
final optsError = libgit2.git_diff_options_init( libgit2.git_diff_options_init(opts, GIT_DIFF_OPTIONS_VERSION);
opts,
GIT_DIFF_OPTIONS_VERSION,
);
if (optsError < 0) {
calloc.free(opts);
throw LibGit2Error(libgit2.git_error_last());
} else {
opts.ref.flags = flags; opts.ref.flags = flags;
opts.ref.context_lines = contextLines; opts.ref.context_lines = contextLines;
opts.ref.interhunk_lines = interhunkLines; opts.ref.interhunk_lines = interhunkLines;
return opts; return opts;
} }
}

View file

@ -14,31 +14,19 @@ import '../util.dart';
/// if it has changed since the last time it was loaded. Purely in-memory index data /// if it has changed since the last time it was loaded. Purely in-memory index data
/// will be untouched. Be aware: if there are changes on disk, unwritten in-memory changes /// will be untouched. Be aware: if there are changes on disk, unwritten in-memory changes
/// are discarded. /// are discarded.
///
/// Throws a [LibGit2Error] if error occured.
void read({required Pointer<git_index> indexPointer, required bool force}) { void read({required Pointer<git_index> indexPointer, required bool force}) {
final forceC = force == true ? 1 : 0; final forceC = force == true ? 1 : 0;
final error = libgit2.git_index_read(indexPointer, forceC); libgit2.git_index_read(indexPointer, forceC);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
} }
/// Read a tree into the index file with stats. /// Read a tree into the index file with stats.
/// ///
/// The current index contents will be replaced by the specified tree. /// The current index contents will be replaced by the specified tree.
///
/// Throws a [LibGit2Error] if error occured.
void readTree({ void readTree({
required Pointer<git_index> indexPointer, required Pointer<git_index> indexPointer,
required Pointer<git_tree> treePointer, required Pointer<git_tree> treePointer,
}) { }) {
final error = libgit2.git_index_read_tree(indexPointer, treePointer); libgit2.git_index_read_tree(indexPointer, treePointer);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
} }
/// Write the index as a tree. /// Write the index as a tree.
@ -243,15 +231,7 @@ void addAll({
} }
/// Write an existing index object from memory back to disk using an atomic file lock. /// Write an existing index object from memory back to disk using an atomic file lock.
/// void write(Pointer<git_index> index) => libgit2.git_index_write(index);
/// Throws a [LibGit2Error] if error occured.
void write(Pointer<git_index> index) {
final error = libgit2.git_index_write(index);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
}
/// Remove an entry from the index. /// Remove an entry from the index.
/// ///
@ -272,8 +252,6 @@ void remove({
} }
/// Remove all matching index entries. /// Remove all matching index entries.
///
/// Throws a [LibGit2Error] if error occured.
void removeAll({ void removeAll({
required Pointer<git_index> indexPointer, required Pointer<git_index> indexPointer,
required List<String> pathspec, required List<String> pathspec,
@ -290,22 +268,13 @@ void removeAll({
pathspecC.ref.strings = strArray; pathspecC.ref.strings = strArray;
pathspecC.ref.count = pathspec.length; pathspecC.ref.count = pathspec.length;
final error = libgit2.git_index_remove_all( libgit2.git_index_remove_all(indexPointer, pathspecC, nullptr, nullptr);
indexPointer,
pathspecC,
nullptr,
nullptr,
);
calloc.free(pathspecC); calloc.free(pathspecC);
for (final p in pathPointers) { for (final p in pathPointers) {
calloc.free(p); calloc.free(p);
} }
calloc.free(strArray); calloc.free(strArray);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
} }
/// Determine if the index contains entries representing file conflicts. /// Determine if the index contains entries representing file conflicts.
@ -320,15 +289,7 @@ List<Map<String, Pointer<git_index_entry>>> conflictList(
Pointer<git_index> index, Pointer<git_index> index,
) { ) {
final iterator = calloc<Pointer<git_index_conflict_iterator>>(); final iterator = calloc<Pointer<git_index_conflict_iterator>>();
final iteratorError = libgit2.git_index_conflict_iterator_new( libgit2.git_index_conflict_iterator_new(iterator, index);
iterator,
index,
);
if (iteratorError < 0) {
calloc.free(iterator);
throw LibGit2Error(libgit2.git_error_last());
}
var result = <Map<String, Pointer<git_index_entry>>>[]; var result = <Map<String, Pointer<git_index_entry>>>[];
var error = 0; var error = 0;

View file

@ -1,3 +1,4 @@
// coverage:ignore-file
// AUTO GENERATED FILE, DO NOT EDIT. // AUTO GENERATED FILE, DO NOT EDIT.
// //
// Generated by `package:ffigen`. // Generated by `package:ffigen`.

View file

@ -8,38 +8,24 @@ import '../util.dart';
/// ///
/// This object is empty, so you'll have to add a mailmap file before you can /// This object is empty, so you'll have to add a mailmap file before you can
/// do anything with it. The mailmap must be freed with `free()`. /// do anything with it. The mailmap must be freed with `free()`.
///
/// Throws a [LibGit2Error] if error occured.
Pointer<git_mailmap> init() { Pointer<git_mailmap> init() {
final out = calloc<Pointer<git_mailmap>>(); final out = calloc<Pointer<git_mailmap>>();
final error = libgit2.git_mailmap_new(out); libgit2.git_mailmap_new(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value; return out.value;
} }
}
/// Create a new mailmap instance containing a single mailmap file. /// Create a new mailmap instance containing a single mailmap file.
///
/// Throws a [LibGit2Error] if error occured.
Pointer<git_mailmap> fromBuffer(String buffer) { Pointer<git_mailmap> fromBuffer(String buffer) {
final out = calloc<Pointer<git_mailmap>>(); final out = calloc<Pointer<git_mailmap>>();
final bufferC = buffer.toNativeUtf8().cast<Int8>(); final bufferC = buffer.toNativeUtf8().cast<Int8>();
final error = libgit2.git_mailmap_from_buffer(out, bufferC, buffer.length); libgit2.git_mailmap_from_buffer(out, bufferC, buffer.length);
calloc.free(bufferC); calloc.free(bufferC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value; return out.value;
} }
}
/// Create a new mailmap instance from a repository, loading mailmap files based /// Create a new mailmap instance from a repository, loading mailmap files based
/// on the repository's configuration. /// on the repository's configuration.
@ -65,8 +51,6 @@ Pointer<git_mailmap> fromRepository(Pointer<git_repository> repo) {
} }
/// Resolve a name and email to the corresponding real name and email. /// Resolve a name and email to the corresponding real name and email.
///
/// Throws a [LibGit2Error] if error occured.
List<String> resolve({ List<String> resolve({
required Pointer<git_mailmap> mailmapPointer, required Pointer<git_mailmap> mailmapPointer,
required String name, required String name,
@ -76,7 +60,7 @@ List<String> resolve({
final outRealEmail = calloc<Pointer<Int8>>(); final outRealEmail = calloc<Pointer<Int8>>();
final nameC = name.toNativeUtf8().cast<Int8>(); final nameC = name.toNativeUtf8().cast<Int8>();
final emailC = email.toNativeUtf8().cast<Int8>(); final emailC = email.toNativeUtf8().cast<Int8>();
final error = libgit2.git_mailmap_resolve( libgit2.git_mailmap_resolve(
outRealName, outRealName,
outRealEmail, outRealEmail,
mailmapPointer, mailmapPointer,
@ -84,13 +68,6 @@ List<String> resolve({
emailC, emailC,
); );
if (error < 0) {
calloc.free(outRealName);
calloc.free(outRealEmail);
calloc.free(nameC);
calloc.free(emailC);
throw LibGit2Error(libgit2.git_error_last());
} else {
final realName = outRealName.value.cast<Utf8>().toDartString(); final realName = outRealName.value.cast<Utf8>().toDartString();
final realEmail = outRealEmail.value.cast<Utf8>().toDartString(); final realEmail = outRealEmail.value.cast<Utf8>().toDartString();
calloc.free(outRealName); calloc.free(outRealName);
@ -100,29 +77,17 @@ List<String> resolve({
return [realName, realEmail]; return [realName, realEmail];
} }
}
/// Resolve a signature to use real names and emails with a mailmap. /// Resolve a signature to use real names and emails with a mailmap.
///
/// Throws a [LibGit2Error] if error occured.
Pointer<git_signature> resolveSignature({ Pointer<git_signature> resolveSignature({
required Pointer<git_mailmap> mailmapPointer, required Pointer<git_mailmap> mailmapPointer,
required Pointer<git_signature> signaturePointer, required Pointer<git_signature> signaturePointer,
}) { }) {
final out = calloc<Pointer<git_signature>>(); final out = calloc<Pointer<git_signature>>();
final error = libgit2.git_mailmap_resolve_signature( libgit2.git_mailmap_resolve_signature(out, mailmapPointer, signaturePointer);
out,
mailmapPointer,
signaturePointer,
);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value; return out.value;
} }
}
/// Add a single entry to the given mailmap object. If the entry already exists, /// Add a single entry to the given mailmap object. If the entry already exists,
/// it will be replaced with the new entry. /// it will be replaced with the new entry.
@ -140,7 +105,7 @@ void addEntry({
final replaceNameC = replaceName?.toNativeUtf8().cast<Int8>() ?? nullptr; final replaceNameC = replaceName?.toNativeUtf8().cast<Int8>() ?? nullptr;
final replaceEmailC = replaceEmail.toNativeUtf8().cast<Int8>(); final replaceEmailC = replaceEmail.toNativeUtf8().cast<Int8>();
final error = libgit2.git_mailmap_add_entry( libgit2.git_mailmap_add_entry(
mailmapPointer, mailmapPointer,
realNameC, realNameC,
realEmailC, realEmailC,
@ -152,10 +117,6 @@ void addEntry({
calloc.free(realEmailC); calloc.free(realEmailC);
calloc.free(replaceNameC); calloc.free(replaceNameC);
calloc.free(replaceEmailC); calloc.free(replaceEmailC);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
} }
/// Free the mailmap and its associated memory. /// Free the mailmap and its associated memory.

View file

@ -25,8 +25,6 @@ Pointer<git_oid> mergeBase({
/// Analyzes the given branch(es) and determines the opportunities for merging them /// Analyzes the given branch(es) and determines the opportunities for merging them
/// into a reference. /// into a reference.
///
/// Throws a [LibGit2Error] if error occured.
List<int> analysis({ List<int> analysis({
required Pointer<git_repository> repoPointer, required Pointer<git_repository> repoPointer,
required Pointer<git_reference> ourRefPointer, required Pointer<git_reference> ourRefPointer,
@ -35,7 +33,7 @@ List<int> analysis({
}) { }) {
final analysisOut = calloc<Int32>(); final analysisOut = calloc<Int32>();
final preferenceOut = calloc<Int32>(); final preferenceOut = calloc<Int32>();
final error = libgit2.git_merge_analysis_for_ref( libgit2.git_merge_analysis_for_ref(
analysisOut, analysisOut,
preferenceOut, preferenceOut,
repoPointer, repoPointer,
@ -43,60 +41,35 @@ List<int> analysis({
theirHeadPointer, theirHeadPointer,
theirHeadsLen, theirHeadsLen,
); );
var result = <int>[];
if (error < 0) { final result = [analysisOut.value, preferenceOut.value];
calloc.free(analysisOut);
calloc.free(preferenceOut);
throw LibGit2Error(libgit2.git_error_last());
} else {
result.add(analysisOut.value);
result.add(preferenceOut.value);
calloc.free(analysisOut); calloc.free(analysisOut);
calloc.free(preferenceOut); calloc.free(preferenceOut);
return result; return result;
} }
}
/// Merges the given commit(s) into HEAD, writing the results into the working directory. /// Merges the given commit(s) into HEAD, writing the results into the working directory.
/// Any changes are staged for commit and any conflicts are written to the index. Callers /// Any changes are staged for commit and any conflicts are written to the index. Callers
/// should inspect the repository's index after this completes, resolve any conflicts and /// should inspect the repository's index after this completes, resolve any conflicts and
/// prepare a commit. /// prepare a commit.
///
/// Throws a [LibGit2Error] if error occured.
void merge({ void merge({
required Pointer<git_repository> repoPointer, required Pointer<git_repository> repoPointer,
required Pointer<Pointer<git_annotated_commit>> theirHeadsPointer, required Pointer<Pointer<git_annotated_commit>> theirHeadsPointer,
required int theirHeadsLen, required int theirHeadsLen,
}) { }) {
final mergeOpts = calloc<git_merge_options>(); final mergeOpts = calloc<git_merge_options>();
final mergeError = libgit2.git_merge_options_init( libgit2.git_merge_options_init(mergeOpts, GIT_MERGE_OPTIONS_VERSION);
mergeOpts,
GIT_MERGE_OPTIONS_VERSION,
);
if (mergeError < 0) {
calloc.free(mergeOpts);
throw LibGit2Error(libgit2.git_error_last());
}
final checkoutOpts = calloc<git_checkout_options>(); final checkoutOpts = calloc<git_checkout_options>();
final checkoutError = libgit2.git_checkout_options_init( libgit2.git_checkout_options_init(checkoutOpts, GIT_CHECKOUT_OPTIONS_VERSION);
checkoutOpts,
GIT_CHECKOUT_OPTIONS_VERSION,
);
if (checkoutError < 0) {
calloc.free(mergeOpts);
calloc.free(checkoutOpts);
throw LibGit2Error(libgit2.git_error_last());
}
checkoutOpts.ref.checkout_strategy = checkoutOpts.ref.checkout_strategy =
git_checkout_strategy_t.GIT_CHECKOUT_SAFE | git_checkout_strategy_t.GIT_CHECKOUT_SAFE |
git_checkout_strategy_t.GIT_CHECKOUT_RECREATE_MISSING; git_checkout_strategy_t.GIT_CHECKOUT_RECREATE_MISSING;
final error = libgit2.git_merge( libgit2.git_merge(
repoPointer, repoPointer,
theirHeadsPointer, theirHeadsPointer,
theirHeadsLen, theirHeadsLen,
@ -106,10 +79,6 @@ void merge({
calloc.free(mergeOpts); calloc.free(mergeOpts);
calloc.free(checkoutOpts); calloc.free(checkoutOpts);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
} }
/// Merge two files as they exist in the index, using the given common ancestor /// Merge two files as they exist in the index, using the given common ancestor
@ -235,15 +204,7 @@ void cherryPick({
required Pointer<git_commit> commitPointer, required Pointer<git_commit> commitPointer,
}) { }) {
final opts = calloc<git_cherrypick_options>(); final opts = calloc<git_cherrypick_options>();
final optsError = libgit2.git_cherrypick_options_init( libgit2.git_cherrypick_options_init(opts, GIT_CHERRYPICK_OPTIONS_VERSION);
opts,
GIT_CHERRYPICK_OPTIONS_VERSION,
);
if (optsError < 0) {
calloc.free(opts);
throw LibGit2Error(libgit2.git_error_last());
}
opts.ref.checkout_opts.checkout_strategy = opts.ref.checkout_opts.checkout_strategy =
git_checkout_strategy_t.GIT_CHECKOUT_SAFE; git_checkout_strategy_t.GIT_CHECKOUT_SAFE;
@ -263,15 +224,7 @@ Pointer<git_merge_options> _initMergeOptions({
required int fileFlags, required int fileFlags,
}) { }) {
final opts = calloc<git_merge_options>(); final opts = calloc<git_merge_options>();
final error = libgit2.git_merge_options_init( libgit2.git_merge_options_init(opts, GIT_MERGE_OPTIONS_VERSION);
opts,
GIT_MERGE_OPTIONS_VERSION,
);
if (error < 0) {
calloc.free(opts);
throw LibGit2Error(libgit2.git_error_last());
}
opts.ref.file_favor = favor; opts.ref.file_favor = favor;
opts.ref.flags = mergeFlags; opts.ref.flags = mergeFlags;

View file

@ -28,18 +28,9 @@ List<Map<String, Pointer>> list(Pointer<git_repository> repo) {
nextError = libgit2.git_note_next(noteOid, annotatedOid, iterator.value); nextError = libgit2.git_note_next(noteOid, annotatedOid, iterator.value);
if (nextError >= 0) { if (nextError >= 0) {
final out = calloc<Pointer<git_note>>(); final out = calloc<Pointer<git_note>>();
final error = libgit2.git_note_read(out, repo, notesRef, annotatedOid); libgit2.git_note_read(out, repo, notesRef, annotatedOid);
calloc.free(noteOid); calloc.free(noteOid);
if (error < 0) {
calloc.free(out);
calloc.free(annotatedOid);
calloc.free(iterator);
throw LibGit2Error(libgit2.git_error_last());
} else {
result.add({'note': out.value, 'annotatedOid': annotatedOid}); result.add({'note': out.value, 'annotatedOid': annotatedOid});
}
} else { } else {
break; break;
} }

View file

@ -10,19 +10,11 @@ import '../util.dart';
/// ///
/// Before the ODB can be used for read/writing, a custom database backend must be /// Before the ODB can be used for read/writing, a custom database backend must be
/// manually added. /// manually added.
///
/// Throws a [LibGit2Error] if error occured.
Pointer<git_odb> create() { Pointer<git_odb> create() {
final out = calloc<Pointer<git_odb>>(); final out = calloc<Pointer<git_odb>>();
final error = libgit2.git_odb_new(out); libgit2.git_odb_new(out);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value; return out.value;
} }
}
/// Add an on-disk alternate to an existing Object DB. /// Add an on-disk alternate to an existing Object DB.
/// ///
@ -33,20 +25,13 @@ Pointer<git_odb> create() {
/// have been exhausted. /// have been exhausted.
/// ///
/// Writing is disabled on alternate backends. /// Writing is disabled on alternate backends.
///
/// Throws a [LibGit2Error] if error occured.
void addDiskAlternate({ void addDiskAlternate({
required Pointer<git_odb> odbPointer, required Pointer<git_odb> odbPointer,
required String path, required String path,
}) { }) {
final pathC = path.toNativeUtf8().cast<Int8>(); final pathC = path.toNativeUtf8().cast<Int8>();
final error = libgit2.git_odb_add_disk_alternate(odbPointer, pathC); libgit2.git_odb_add_disk_alternate(odbPointer, pathC);
calloc.free(pathC); calloc.free(pathC);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
} }
/// Determine if an object can be found in the object database by an abbreviated object ID. /// Determine if an object can be found in the object database by an abbreviated object ID.
@ -174,7 +159,7 @@ void objectFree(Pointer<git_odb_object> object) {
libgit2.git_odb_object_free(object); libgit2.git_odb_object_free(object);
} }
/// Write raw data to into the object database. /// Write raw data into the object database.
/// ///
/// Throws a [LibGit2Error] if error occured. /// Throws a [LibGit2Error] if error occured.
Pointer<git_oid> write({ Pointer<git_oid> write({
@ -196,55 +181,16 @@ Pointer<git_oid> write({
} }
final buffer = data.toNativeUtf8().cast<Int8>(); final buffer = data.toNativeUtf8().cast<Int8>();
final writeError = libgit2.git_odb_stream_write( libgit2.git_odb_stream_write(stream.value, buffer, data.length);
stream.value,
buffer,
data.length,
);
if (writeError < 0) {
calloc.free(buffer);
libgit2.git_odb_stream_free(stream.value);
throw LibGit2Error(libgit2.git_error_last());
}
final out = calloc<git_oid>(); final out = calloc<git_oid>();
final finalizeError = libgit2.git_odb_stream_finalize_write( libgit2.git_odb_stream_finalize_write(out, stream.value);
out,
stream.value,
);
calloc.free(buffer); calloc.free(buffer);
libgit2.git_odb_stream_free(stream.value); libgit2.git_odb_stream_free(stream.value);
if (finalizeError < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out; return out;
} }
}
/// Get the number of ODB backend objects.
int backendsCount(Pointer<git_odb> odb) => libgit2.git_odb_num_backends(odb);
/// Lookup an ODB backend object by index.
///
/// Throws a [LibGit2Error] if error occured.
Pointer<git_odb_backend> getBackend({
required Pointer<git_odb> odbPointer,
required int position,
}) {
final out = calloc<Pointer<git_odb_backend>>();
final error = libgit2.git_odb_get_backend(out, odbPointer, position);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
}
}
/// Close an open object database. /// Close an open object database.
void free(Pointer<git_odb> db) => libgit2.git_odb_free(db); void free(Pointer<git_odb> db) => libgit2.git_odb_free(db);

View file

@ -1,84 +1,55 @@
import 'dart:ffi'; import 'dart:ffi';
import 'package:ffi/ffi.dart'; import 'package:ffi/ffi.dart';
import '../error.dart';
import 'libgit2_bindings.dart'; import 'libgit2_bindings.dart';
import '../util.dart'; import '../util.dart';
/// Parse N characters of a hex formatted object id into a git_oid. /// Parse N characters of a hex formatted object id into a git_oid.
///
/// If N is odd, the last byte's high nibble will be read in and the low nibble set to zero.
///
/// Throws a [LibGit2Error] if error occured.
Pointer<git_oid> fromStrN(String hex) { Pointer<git_oid> fromStrN(String hex) {
final out = calloc<git_oid>(); final out = calloc<git_oid>();
final str = hex.toNativeUtf8().cast<Int8>(); final str = hex.toNativeUtf8().cast<Int8>();
final error = libgit2.git_oid_fromstrn(out, str, hex.length); libgit2.git_oid_fromstrn(out, str, hex.length);
calloc.free(str); calloc.free(str);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out; return out;
} }
}
/// Parse a hex formatted object id into a git_oid. /// Parse a hex formatted object id into a git_oid.
///
/// Throws a [LibGit2Error] if error occured.
Pointer<git_oid> fromSHA(String hex) { Pointer<git_oid> fromSHA(String hex) {
final out = calloc<git_oid>(); final out = calloc<git_oid>();
final str = hex.toNativeUtf8().cast<Int8>(); final str = hex.toNativeUtf8().cast<Int8>();
final error = libgit2.git_oid_fromstr(out, str); libgit2.git_oid_fromstr(out, str);
calloc.free(str); calloc.free(str);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out; return out;
} }
}
/// Copy an already raw oid into a git_oid structure. /// Copy an already raw oid into a git_oid structure.
///
/// Throws a [LibGit2Error] if error occured.
Pointer<git_oid> fromRaw(Array<Uint8> raw) { Pointer<git_oid> fromRaw(Array<Uint8> raw) {
final out = calloc<git_oid>(); final out = calloc<git_oid>();
var rawC = calloc<Uint8>(20); var rawC = calloc<Uint8>(20);
for (var i = 0; i < 20; i++) { for (var i = 0; i < 20; i++) {
rawC[i] = raw[i]; rawC[i] = raw[i];
} }
final error = libgit2.git_oid_fromraw(out, rawC);
libgit2.git_oid_fromraw(out, rawC);
calloc.free(rawC); calloc.free(rawC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out; return out;
} }
}
/// Format a git_oid into a hex string. /// Format a git_oid into a hex string.
///
/// Throws a [LibGit2Error] if error occured.
String toSHA(Pointer<git_oid> id) { String toSHA(Pointer<git_oid> id) {
final out = calloc<Int8>(40); final out = calloc<Int8>(40);
final error = libgit2.git_oid_fmt(out, id); libgit2.git_oid_fmt(out, id);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
final result = out.cast<Utf8>().toDartString(length: 40); final result = out.cast<Utf8>().toDartString(length: 40);
calloc.free(out); calloc.free(out);
return result; return result;
} }
}
/// Compare two oid structures. /// Compare two oid structures.
/// ///
@ -91,16 +62,8 @@ int compare({
} }
/// Copy an oid from one structure to another. /// Copy an oid from one structure to another.
///
/// Throws a [LibGit2Error] if error occured.
Pointer<git_oid> copy(Pointer<git_oid> src) { Pointer<git_oid> copy(Pointer<git_oid> src) {
final out = calloc<git_oid>(); final out = calloc<git_oid>();
final error = libgit2.git_oid_cpy(out, src); libgit2.git_oid_cpy(out, src);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out; return out;
} }
}

View file

@ -7,9 +7,7 @@ import '../util.dart';
/// Directly generate a patch from the difference between two buffers. /// Directly generate a patch from the difference between two buffers.
/// ///
/// You can use the standard patch accessor functions to read the patch data, and /// You can use the standard patch accessor functions to read the patch data, and
/// you must call `free()` on the patch when done. /// you must free the patch when done.
///
/// Throws a [LibGit2Error] if error occured.
Map<String, Pointer?> fromBuffers({ Map<String, Pointer?> fromBuffers({
String? oldBuffer, String? oldBuffer,
String? oldAsPath, String? oldAsPath,
@ -32,7 +30,7 @@ Map<String, Pointer?> fromBuffers({
interhunkLines: interhunkLines, interhunkLines: interhunkLines,
); );
final error = libgit2.git_patch_from_buffers( libgit2.git_patch_from_buffers(
out, out,
oldBufferC.cast(), oldBufferC.cast(),
oldLen, oldLen,
@ -47,29 +45,20 @@ Map<String, Pointer?> fromBuffers({
calloc.free(newAsPathC); calloc.free(newAsPathC);
calloc.free(opts); calloc.free(opts);
if (error < 0) {
calloc.free(out);
calloc.free(oldBufferC);
calloc.free(newBufferC);
throw LibGit2Error(libgit2.git_error_last());
} else {
// Returning map with pointers to patch and buffers because patch object does not // Returning map with pointers to patch and buffers because patch object does not
// have refenrece to underlying buffers or blobs. So if the buffer or blob is freed/removed // have refenrece to underlying buffers or blobs. So if the buffer or blob is freed/removed
// the patch text becomes corrupted. // the patch text becomes corrupted.
return {'patch': out.value, 'a': oldBufferC, 'b': newBufferC}; return {'patch': out.value, 'a': oldBufferC, 'b': newBufferC};
} }
}
/// Directly generate a patch from the difference between two blobs. /// Directly generate a patch from the difference between two blobs.
/// ///
/// You can use the standard patch accessor functions to read the patch data, and you /// You can use the standard patch accessor functions to read the patch data, and you
/// must call `free()` on the patch when done. /// must free the patch when done.
///
/// Throws a [LibGit2Error] if error occured.
Map<String, Pointer?> fromBlobs({ Map<String, Pointer?> fromBlobs({
Pointer<git_blob>? oldBlobPointer, required Pointer<git_blob> oldBlobPointer,
String? oldAsPath, String? oldAsPath,
Pointer<git_blob>? newBlobPointer, required Pointer<git_blob> newBlobPointer,
String? newAsPath, String? newAsPath,
required int flags, required int flags,
required int contextLines, required int contextLines,
@ -84,11 +73,11 @@ Map<String, Pointer?> fromBlobs({
interhunkLines: interhunkLines, interhunkLines: interhunkLines,
); );
final error = libgit2.git_patch_from_blobs( libgit2.git_patch_from_blobs(
out, out,
oldBlobPointer ?? nullptr, oldBlobPointer,
oldAsPathC, oldAsPathC,
newBlobPointer ?? nullptr, newBlobPointer,
newAsPathC, newAsPathC,
opts, opts,
); );
@ -97,23 +86,16 @@ Map<String, Pointer?> fromBlobs({
calloc.free(newAsPathC); calloc.free(newAsPathC);
calloc.free(opts); calloc.free(opts);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
// Returning map with pointers to patch and blobs because patch object does not // Returning map with pointers to patch and blobs because patch object does not
// have reference to underlying blobs. So if the blob is freed/removed the patch // have reference to underlying blobs. So if the blob is freed/removed the patch
// text becomes corrupted. // text becomes corrupted.
return {'patch': out.value, 'a': oldBlobPointer, 'b': newBlobPointer}; return {'patch': out.value, 'a': oldBlobPointer, 'b': newBlobPointer};
} }
}
/// Directly generate a patch from the difference between a blob and a buffer. /// Directly generate a patch from the difference between a blob and a buffer.
/// ///
/// You can use the standard patch accessor functions to read the patch data, and you must /// You can use the standard patch accessor functions to read the patch data, and you must
/// call `free()` on the patch when done. /// free the patch when done.
///
/// Throws a [LibGit2Error] if error occured.
Map<String, Pointer?> fromBlobAndBuffer({ Map<String, Pointer?> fromBlobAndBuffer({
Pointer<git_blob>? oldBlobPointer, Pointer<git_blob>? oldBlobPointer,
String? oldAsPath, String? oldAsPath,
@ -134,7 +116,7 @@ Map<String, Pointer?> fromBlobAndBuffer({
interhunkLines: interhunkLines, interhunkLines: interhunkLines,
); );
final error = libgit2.git_patch_from_blob_and_buffer( libgit2.git_patch_from_blob_and_buffer(
out, out,
oldBlobPointer ?? nullptr, oldBlobPointer ?? nullptr,
oldAsPathC, oldAsPathC,
@ -148,17 +130,11 @@ Map<String, Pointer?> fromBlobAndBuffer({
calloc.free(bufferAsPathC); calloc.free(bufferAsPathC);
calloc.free(opts); calloc.free(opts);
if (error < 0) {
calloc.free(out);
calloc.free(bufferC);
throw LibGit2Error(libgit2.git_error_last());
} else {
// Returning map with pointers to patch and buffers because patch object does not // Returning map with pointers to patch and buffers because patch object does not
// have reference to underlying buffers or blobs. So if the buffer or blob is freed/removed // have reference to underlying buffers or blobs. So if the buffer or blob is freed/removed
// the patch text becomes corrupted. // the patch text becomes corrupted.
return {'patch': out.value, 'a': oldBlobPointer, 'b': bufferC}; return {'patch': out.value, 'a': oldBlobPointer, 'b': bufferC};
} }
}
/// Return a patch for an entry in the diff list. /// Return a patch for an entry in the diff list.
/// ///
@ -191,56 +167,32 @@ int numHunks(Pointer<git_patch> patch) => libgit2.git_patch_num_hunks(patch);
/// Get the information about a hunk in a patch. /// Get the information about a hunk in a patch.
/// ///
/// Given a patch and a hunk index into the patch, this returns detailed information about that hunk. /// Given a patch and a hunk index into the patch, this returns detailed information
/// /// about that hunk.
/// Throws a [LibGit2Error] if error occured.
Map<String, Object> hunk({ Map<String, Object> hunk({
required Pointer<git_patch> patchPointer, required Pointer<git_patch> patchPointer,
required int hunkIndex, required int hunkIndex,
}) { }) {
final out = calloc<Pointer<git_diff_hunk>>(); final out = calloc<Pointer<git_diff_hunk>>();
final linesInHunk = calloc<Int64>(); final linesInHunk = calloc<Int64>();
final error = libgit2.git_patch_get_hunk( libgit2.git_patch_get_hunk(out, linesInHunk.cast(), patchPointer, hunkIndex);
out,
linesInHunk.cast(),
patchPointer,
hunkIndex,
);
if (error < 0) {
calloc.free(out);
calloc.free(linesInHunk);
throw LibGit2Error(libgit2.git_error_last());
} else {
final linesN = linesInHunk.value; final linesN = linesInHunk.value;
calloc.free(linesInHunk); calloc.free(linesInHunk);
return {'hunk': out.value, 'linesN': linesN}; return {'hunk': out.value, 'linesN': linesN};
} }
}
/// Get data about a line in a hunk of a patch. /// Get data about a line in a hunk of a patch.
///
/// Throws a [LibGit2Error] if error occured.
Pointer<git_diff_line> lines({ Pointer<git_diff_line> lines({
required Pointer<git_patch> patchPointer, required Pointer<git_patch> patchPointer,
required int hunkIndex, required int hunkIndex,
required int lineOfHunk, required int lineOfHunk,
}) { }) {
final out = calloc<Pointer<git_diff_line>>(); final out = calloc<Pointer<git_diff_line>>();
final error = libgit2.git_patch_get_line_in_hunk( libgit2.git_patch_get_line_in_hunk(out, patchPointer, hunkIndex, lineOfHunk);
out,
patchPointer,
hunkIndex,
lineOfHunk,
);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value; return out.value;
} }
}
/// Get the content of a patch as a single diff text. /// Get the content of a patch as a single diff text.
/// ///
@ -294,15 +246,7 @@ Pointer<git_diff_options> _diffOptionsInit({
required int interhunkLines, required int interhunkLines,
}) { }) {
final opts = calloc<git_diff_options>(); final opts = calloc<git_diff_options>();
final optsError = libgit2.git_diff_options_init( libgit2.git_diff_options_init(opts, GIT_DIFF_OPTIONS_VERSION);
opts,
GIT_DIFF_OPTIONS_VERSION,
);
if (optsError < 0) {
calloc.free(opts);
throw LibGit2Error(libgit2.git_error_last());
}
opts.ref.flags = flags; opts.ref.flags = flags;
opts.ref.context_lines = contextLines; opts.ref.context_lines = contextLines;

View file

@ -25,16 +25,7 @@ Pointer<git_rebase> init({
final out = calloc<Pointer<git_rebase>>(); final out = calloc<Pointer<git_rebase>>();
final opts = calloc<git_rebase_options>(); final opts = calloc<git_rebase_options>();
final optsError = libgit2.git_rebase_options_init( libgit2.git_rebase_options_init(opts, GIT_REBASE_OPTIONS_VERSION);
opts,
GIT_REBASE_OPTIONS_VERSION,
);
if (optsError < 0) {
calloc.free(out);
calloc.free(opts);
throw LibGit2Error(libgit2.git_error_last());
}
final error = libgit2.git_rebase_init( final error = libgit2.git_rebase_init(
out, out,
@ -110,27 +101,12 @@ void commit({
} }
/// Finishes a rebase that is currently in progress once all patches have been applied. /// Finishes a rebase that is currently in progress once all patches have been applied.
/// void finish(Pointer<git_rebase> rebase) =>
/// Throws a [LibGit2Error] if error occured. libgit2.git_rebase_finish(rebase, nullptr);
void finish(Pointer<git_rebase> rebase) {
final error = libgit2.git_rebase_finish(rebase, nullptr);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
}
/// Aborts a rebase that is currently in progress, resetting the repository and working /// Aborts a rebase that is currently in progress, resetting the repository and working
/// directory to their state before rebase began. /// directory to their state before rebase began.
/// void abort(Pointer<git_rebase> rebase) => libgit2.git_rebase_abort(rebase);
/// Throws a [LibGit2Error] if error occured.
void abort(Pointer<git_rebase> rebase) {
final error = libgit2.git_rebase_abort(rebase);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
}
/// Free memory allocated for rebase object. /// Free memory allocated for rebase object.
void free(Pointer<git_rebase> rebase) => libgit2.git_rebase_free(rebase); void free(Pointer<git_rebase> rebase) => libgit2.git_rebase_free(rebase);

View file

@ -1,20 +1,11 @@
import 'dart:ffi'; import 'dart:ffi';
import '../error.dart';
import 'libgit2_bindings.dart'; import 'libgit2_bindings.dart';
import '../util.dart'; import '../util.dart';
/// Suggests that the given refdb compress or optimize its references. /// Suggests that the given refdb compress or optimize its references.
/// This mechanism is implementation specific. For on-disk reference databases, /// This mechanism is implementation specific. For on-disk reference databases,
/// for example, this may pack all loose references. /// for example, this may pack all loose references.
/// void compress(Pointer<git_refdb> refdb) => libgit2.git_refdb_compress(refdb);
/// Throws a [LibGit2Error] if error occured.
void compress(Pointer<git_refdb> refdb) {
final error = libgit2.git_refdb_compress(refdb);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
}
/// Close an open reference database to release memory. /// Close an open reference database to release memory.
void free(Pointer<git_refdb> refdb) => libgit2.git_refdb_free(refdb); void free(Pointer<git_refdb> refdb) => libgit2.git_refdb_free(refdb);

View file

@ -13,17 +13,8 @@ int referenceType(Pointer<git_reference> ref) =>
/// Get the OID pointed to by a direct reference. /// Get the OID pointed to by a direct reference.
/// ///
/// Only available if the reference is direct (i.e. an object id reference, not a symbolic one). /// Only available if the reference is direct (i.e. an object id reference, not a symbolic one).
/// Pointer<git_oid> target(Pointer<git_reference> ref) =>
/// Throws an exception if error occured. libgit2.git_reference_target(ref);
Pointer<git_oid> target(Pointer<git_reference> ref) {
final result = libgit2.git_reference_target(ref);
if (result == nullptr) {
throw Exception('Oid for reference isn\'t available');
} else {
return result;
}
}
/// Resolve a symbolic reference to a direct reference. /// Resolve a symbolic reference to a direct reference.
/// ///
@ -73,30 +64,6 @@ Pointer<git_reference> lookup({
} }
} }
/// Lookup a reference by DWIMing its short name.
///
/// Apply the git precendence rules to the given shorthand to determine which reference
/// the user is referring to.
///
/// Throws a [LibGit2Error] if error occured.
Pointer<git_reference> lookupDWIM({
required Pointer<git_repository> repoPointer,
required String name,
}) {
final out = calloc<Pointer<git_reference>>();
final nameC = name.toNativeUtf8().cast<Int8>();
final error = libgit2.git_reference_dwim(out, repoPointer, nameC);
calloc.free(nameC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
}
}
/// Get the full name of a reference. /// Get the full name of a reference.
String name(Pointer<git_reference> ref) { String name(Pointer<git_reference> ref) {
return libgit2.git_reference_name(ref).cast<Utf8>().toDartString(); return libgit2.git_reference_name(ref).cast<Utf8>().toDartString();
@ -175,22 +142,16 @@ List<String> list(Pointer<git_repository> repo) {
} }
/// Check if a reflog exists for the specified reference. /// Check if a reflog exists for the specified reference.
///
/// Throws a [LibGit2Error] if error occured.
bool hasLog({ bool hasLog({
required Pointer<git_repository> repoPointer, required Pointer<git_repository> repoPointer,
required String name, required String name,
}) { }) {
final refname = name.toNativeUtf8().cast<Int8>(); final refname = name.toNativeUtf8().cast<Int8>();
final error = libgit2.git_reference_has_log(repoPointer, refname); final result = libgit2.git_reference_has_log(repoPointer, refname);
calloc.free(refname); calloc.free(refname);
if (error < 0) { return result == 1 ? true : false;
throw LibGit2Error(libgit2.git_error_last());
} else {
return error == 1 ? true : false;
}
} }
/// Check if a reference is a local branch. /// Check if a reference is a local branch.
@ -329,15 +290,7 @@ Pointer<git_reference> createSymbolic({
/// ///
/// This method works for both direct and symbolic references. /// This method works for both direct and symbolic references.
/// The reference will be immediately removed on disk but the memory will not be freed. /// The reference will be immediately removed on disk but the memory will not be freed.
/// void delete(Pointer<git_reference> ref) => libgit2.git_reference_delete(ref);
/// Throws a [LibGit2Error] if the reference has changed from the time it was looked up.
void delete(Pointer<git_reference> ref) {
final error = libgit2.git_reference_delete(ref);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
}
/// Get the repository where a reference resides. /// Get the repository where a reference resides.
Pointer<git_repository> owner(Pointer<git_reference> ref) { Pointer<git_repository> owner(Pointer<git_reference> ref) {
@ -444,23 +397,5 @@ Pointer<git_object> peel({
} }
} }
/// Ensure the reference name is well-formed.
///
/// Valid reference names 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").
/// Names prefixed with "refs/" can be almost anything. You must avoid
/// the characters '~', '^', ':', '\', '?', '[', and '*', and the sequences ".."
/// and "@{" which have special meaning to revparse.
bool isValidName(String name) {
final refname = name.toNativeUtf8().cast<Int8>();
final result = libgit2.git_reference_is_valid_name(refname);
calloc.free(refname);
return result == 1 ? true : false;
}
/// Free the given reference. /// Free the given reference.
void free(Pointer<git_reference> ref) => libgit2.git_reference_free(ref); void free(Pointer<git_reference> ref) => libgit2.git_reference_free(ref);

View file

@ -1,6 +1,5 @@
import 'dart:ffi'; import 'dart:ffi';
import 'package:ffi/ffi.dart'; import 'package:ffi/ffi.dart';
import '../error.dart';
import 'libgit2_bindings.dart'; import 'libgit2_bindings.dart';
import '../util.dart'; import '../util.dart';
@ -10,25 +9,18 @@ import '../util.dart';
/// object will be returned. /// object will be returned.
/// ///
/// The reflog must be freed manually. /// The reflog must be freed manually.
///
/// Throws a [LibGit2Error] if error occured.
Pointer<git_reflog> read({ Pointer<git_reflog> read({
required Pointer<git_repository> repoPointer, required Pointer<git_repository> repoPointer,
required String name, required String name,
}) { }) {
final out = calloc<Pointer<git_reflog>>(); final out = calloc<Pointer<git_reflog>>();
final nameC = name.toNativeUtf8().cast<Int8>(); final nameC = name.toNativeUtf8().cast<Int8>();
final error = libgit2.git_reflog_read(out, repoPointer, nameC); libgit2.git_reflog_read(out, repoPointer, nameC);
calloc.free(nameC); calloc.free(nameC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value; return out.value;
} }
}
/// Get the number of log entries in a reflog. /// Get the number of log entries in a reflog.
int entryCount(Pointer<git_reflog> reflog) => int entryCount(Pointer<git_reflog> reflog) =>

View file

@ -12,20 +12,17 @@ import 'remote_callbacks.dart';
/// Throws a [LibGit2Error] if error occured. /// Throws a [LibGit2Error] if error occured.
List<String> list(Pointer<git_repository> repo) { List<String> list(Pointer<git_repository> repo) {
final out = calloc<git_strarray>(); final out = calloc<git_strarray>();
final error = libgit2.git_remote_list(out, repo); libgit2.git_remote_list(out, repo);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
var result = <String>[]; var result = <String>[];
for (var i = 0; i < out.ref.count; i++) { for (var i = 0; i < out.ref.count; i++) {
result.add(out.ref.strings[i].cast<Utf8>().toDartString()); result.add(out.ref.strings[i].cast<Utf8>().toDartString());
} }
calloc.free(out); calloc.free(out);
return result; return result;
} }
}
/// Get the information for a particular remote. /// Get the information for a particular remote.
/// ///
@ -210,11 +207,6 @@ void setPushUrl({
} }
} }
/// Get the remote's repository.
Pointer<git_repository> owner(Pointer<git_remote> remote) {
return libgit2.git_remote_owner(remote);
}
/// Get the remote's name. /// Get the remote's name.
String name(Pointer<git_remote> remote) { String name(Pointer<git_remote> remote) {
final result = libgit2.git_remote_name(remote); final result = libgit2.git_remote_name(remote);
@ -332,7 +324,7 @@ void connect({
String? proxyOption, String? proxyOption,
}) { }) {
final callbacksOptions = calloc<git_remote_callbacks>(); final callbacksOptions = calloc<git_remote_callbacks>();
final callbacksError = libgit2.git_remote_init_callbacks( libgit2.git_remote_init_callbacks(
callbacksOptions, callbacksOptions,
GIT_REMOTE_CALLBACKS_VERSION, GIT_REMOTE_CALLBACKS_VERSION,
); );
@ -342,10 +334,6 @@ void connect({
callbacks: callbacks, callbacks: callbacks,
); );
if (callbacksError < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
final proxyOptions = _proxyOptionsInit(proxyOption); final proxyOptions = _proxyOptionsInit(proxyOption);
final error = libgit2.git_remote_connect( final error = libgit2.git_remote_connect(
@ -377,26 +365,17 @@ void connect({
List<Map<String, Object?>> lsRemotes(Pointer<git_remote> remote) { List<Map<String, Object?>> lsRemotes(Pointer<git_remote> remote) {
final out = calloc<Pointer<Pointer<git_remote_head>>>(); final out = calloc<Pointer<Pointer<git_remote_head>>>();
final size = calloc<Uint64>(); final size = calloc<Uint64>();
final error = libgit2.git_remote_ls(out, size, remote); libgit2.git_remote_ls(out, size, remote);
if (error < 0) {
calloc.free(out);
calloc.free(size);
throw LibGit2Error(libgit2.git_error_last());
} else {
var result = <Map<String, Object?>>[]; var result = <Map<String, Object?>>[];
for (var i = 0; i < size.value; i++) { for (var i = 0; i < size.value; i++) {
var remote = <String, Object?>{}; var remote = <String, Object?>{};
Oid? loid;
final bool local = out[0][i].ref.local == 1 ? true : false; final local = out[0][i].ref.local == 1 ? true : false;
if (local) {
loid = Oid.fromRaw(out[0][i].ref.loid);
}
remote['local'] = local; remote['local'] = local;
remote['loid'] = loid; remote['loid'] = local ? Oid.fromRaw(out[0][i].ref.loid) : null;
remote['name'] = out[0][i].ref.name == nullptr remote['name'] = out[0][i].ref.name == nullptr
? '' ? ''
: out[0][i].ref.name.cast<Utf8>().toDartString(); : out[0][i].ref.name.cast<Utf8>().toDartString();
@ -413,7 +392,6 @@ List<Map<String, Object?>> lsRemotes(Pointer<git_remote> remote) {
return result; return result;
} }
}
/// Download new data and update tips. /// Download new data and update tips.
/// ///
@ -445,22 +423,7 @@ void fetch({
final proxyOptions = _proxyOptionsInit(proxyOption); final proxyOptions = _proxyOptionsInit(proxyOption);
final opts = calloc<git_fetch_options>(); final opts = calloc<git_fetch_options>();
final optsError = libgit2.git_fetch_options_init( libgit2.git_fetch_options_init(opts, GIT_FETCH_OPTIONS_VERSION);
opts,
GIT_FETCH_OPTIONS_VERSION,
);
if (optsError < 0) {
for (final p in refspecsPointers) {
calloc.free(p);
}
calloc.free(refspecsC);
calloc.free(strArray);
calloc.free(proxyOptions);
calloc.free(reflogMessageC);
calloc.free(opts);
throw LibGit2Error(libgit2.git_error_last());
}
RemoteCallbacks.plug( RemoteCallbacks.plug(
callbacksOptions: opts.ref.callbacks, callbacksOptions: opts.ref.callbacks,
@ -515,20 +478,8 @@ void push({
final proxyOptions = _proxyOptionsInit(proxyOption); final proxyOptions = _proxyOptionsInit(proxyOption);
final opts = calloc<git_push_options>(); final opts = calloc<git_push_options>();
final optsError =
libgit2.git_push_options_init(opts, GIT_PUSH_OPTIONS_VERSION); libgit2.git_push_options_init(opts, GIT_PUSH_OPTIONS_VERSION);
if (optsError < 0) {
for (final p in refspecsPointers) {
calloc.free(p);
}
calloc.free(strArray);
calloc.free(refspecsC);
calloc.free(proxyOptions);
calloc.free(opts);
throw LibGit2Error(libgit2.git_error_last());
}
RemoteCallbacks.plug( RemoteCallbacks.plug(
callbacksOptions: opts.ref.callbacks, callbacksOptions: opts.ref.callbacks,
callbacks: callbacks, callbacks: callbacks,
@ -556,15 +507,8 @@ Pointer<git_indexer_progress> stats(Pointer<git_remote> remote) =>
libgit2.git_remote_stats(remote); libgit2.git_remote_stats(remote);
/// Close the connection to the remote. /// Close the connection to the remote.
/// void disconnect(Pointer<git_remote> remote) =>
/// Throws a [LibGit2Error] if error occured. libgit2.git_remote_disconnect(remote);
void disconnect(Pointer<git_remote> remote) {
final error = libgit2.git_remote_disconnect(remote);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
}
/// Prune tracking refs that are no longer present on remote. /// Prune tracking refs that are no longer present on remote.
/// ///
@ -574,16 +518,11 @@ void prune({
required Callbacks callbacks, required Callbacks callbacks,
}) { }) {
final callbacksOptions = calloc<git_remote_callbacks>(); final callbacksOptions = calloc<git_remote_callbacks>();
final callbacksError = libgit2.git_remote_init_callbacks( libgit2.git_remote_init_callbacks(
callbacksOptions, callbacksOptions,
GIT_REMOTE_CALLBACKS_VERSION, GIT_REMOTE_CALLBACKS_VERSION,
); );
if (callbacksError < 0) {
calloc.free(callbacksOptions);
throw LibGit2Error(libgit2.git_error_last());
}
RemoteCallbacks.plug( RemoteCallbacks.plug(
callbacksOptions: callbacksOptions.ref, callbacksOptions: callbacksOptions.ref,
callbacks: callbacks, callbacks: callbacks,
@ -608,14 +547,8 @@ void free(Pointer<git_remote> remote) => libgit2.git_remote_free(remote);
/// Initializes git_proxy_options structure. /// Initializes git_proxy_options structure.
Pointer<git_proxy_options> _proxyOptionsInit(String? proxyOption) { Pointer<git_proxy_options> _proxyOptionsInit(String? proxyOption) {
final proxyOptions = calloc<git_proxy_options>(); final proxyOptions = calloc<git_proxy_options>();
final proxyOptionsError =
libgit2.git_proxy_options_init(proxyOptions, GIT_PROXY_OPTIONS_VERSION); libgit2.git_proxy_options_init(proxyOptions, GIT_PROXY_OPTIONS_VERSION);
if (proxyOptionsError < 0) {
calloc.free(proxyOptions);
throw LibGit2Error(libgit2.git_error_last());
}
if (proxyOption == null) { if (proxyOption == null) {
proxyOptions.ref.type = git_proxy_t.GIT_PROXY_NONE; proxyOptions.ref.type = git_proxy_t.GIT_PROXY_NONE;
} else if (proxyOption == 'auto') { } else if (proxyOption == 'auto') {

View file

@ -28,33 +28,11 @@ Pointer<git_repository> open(String path) {
} }
} }
/// Attempt to open an already-existing bare repository at [bare_path].
///
/// The [bare_path] can point to only a bare repository.
///
/// Throws a [LibGit2Error] if error occured.
Pointer<git_repository> openBare(String barePath) {
final out = calloc<Pointer<git_repository>>();
final barePathC = barePath.toNativeUtf8().cast<Int8>();
final error = libgit2.git_repository_open_bare(out, barePathC);
calloc.free(barePathC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
}
}
/// Look for a git repository and return its path. The lookup start from [startPath] /// Look for a git repository and return its path. The lookup start from [startPath]
/// and walk across parent directories if nothing has been found. The lookup ends when /// and walk across parent directories if nothing has been found. The lookup ends when
/// the first repository is found, or when reaching a directory referenced in [ceilingDirs]. /// the first repository is found, or when reaching a directory referenced in [ceilingDirs].
/// ///
/// The method will automatically detect if the repository is bare (if there is a repository). /// The method will automatically detect if the repository is bare (if there is a repository).
///
/// Throws a [LibGit2Error] if error occured.
String discover({ String discover({
required String startPath, required String startPath,
String? ceilingDirs, String? ceilingDirs,
@ -63,28 +41,15 @@ String discover({
final startPathC = startPath.toNativeUtf8().cast<Int8>(); final startPathC = startPath.toNativeUtf8().cast<Int8>();
final ceilingDirsC = ceilingDirs?.toNativeUtf8().cast<Int8>() ?? nullptr; final ceilingDirsC = ceilingDirs?.toNativeUtf8().cast<Int8>() ?? nullptr;
final error = libgit2.git_repository_discover( libgit2.git_repository_discover(out, startPathC, 0, ceilingDirsC);
out,
startPathC,
0,
ceilingDirsC,
);
calloc.free(startPathC); calloc.free(startPathC);
calloc.free(ceilingDirsC); calloc.free(ceilingDirsC);
if (error == git_error_code.GIT_ENOTFOUND) {
calloc.free(out);
return '';
} else if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
final result = out.ref.ptr.cast<Utf8>().toDartString(); final result = out.ref.ptr.cast<Utf8>().toDartString();
calloc.free(out); calloc.free(out);
return result; return result;
} }
}
/// Creates a new Git repository in the given folder. /// Creates a new Git repository in the given folder.
/// ///
@ -107,23 +72,11 @@ Pointer<git_repository> init({
final initialHeadC = initialHead?.toNativeUtf8().cast<Int8>() ?? nullptr; final initialHeadC = initialHead?.toNativeUtf8().cast<Int8>() ?? nullptr;
final originUrlC = originUrl?.toNativeUtf8().cast<Int8>() ?? nullptr; final originUrlC = originUrl?.toNativeUtf8().cast<Int8>() ?? nullptr;
final opts = calloc<git_repository_init_options>(); final opts = calloc<git_repository_init_options>();
final optsError = libgit2.git_repository_init_options_init( libgit2.git_repository_init_options_init(
opts, opts,
GIT_REPOSITORY_INIT_OPTIONS_VERSION, GIT_REPOSITORY_INIT_OPTIONS_VERSION,
); );
if (optsError < 0) {
calloc.free(out);
calloc.free(pathC);
calloc.free(workdirPathC);
calloc.free(descriptionC);
calloc.free(templatePathC);
calloc.free(initialHeadC);
calloc.free(originUrlC);
calloc.free(opts);
throw LibGit2Error(libgit2.git_error_last());
}
opts.ref.flags = flags; opts.ref.flags = flags;
opts.ref.mode = mode; opts.ref.mode = mode;
opts.ref.workdir_path = workdirPathC; opts.ref.workdir_path = workdirPathC;
@ -169,32 +122,11 @@ Pointer<git_repository> clone({
checkoutBranch?.toNativeUtf8().cast<Int8>() ?? nullptr; checkoutBranch?.toNativeUtf8().cast<Int8>() ?? nullptr;
final cloneOptions = calloc<git_clone_options>(); final cloneOptions = calloc<git_clone_options>();
final cloneOptionsError =
libgit2.git_clone_options_init(cloneOptions, GIT_CLONE_OPTIONS_VERSION); libgit2.git_clone_options_init(cloneOptions, GIT_CLONE_OPTIONS_VERSION);
if (cloneOptionsError < 0) {
calloc.free(out);
calloc.free(urlC);
calloc.free(localPathC);
calloc.free(checkoutBranchC);
calloc.free(cloneOptions);
throw LibGit2Error(libgit2.git_error_last());
}
final fetchOptions = calloc<git_fetch_options>(); final fetchOptions = calloc<git_fetch_options>();
final fetchOptionsError =
libgit2.git_fetch_options_init(fetchOptions, GIT_FETCH_OPTIONS_VERSION); libgit2.git_fetch_options_init(fetchOptions, GIT_FETCH_OPTIONS_VERSION);
if (fetchOptionsError < 0) {
calloc.free(out);
calloc.free(urlC);
calloc.free(localPathC);
calloc.free(checkoutBranchC);
calloc.free(cloneOptions);
calloc.free(fetchOptions);
throw LibGit2Error(libgit2.git_error_last());
}
RemoteCallbacks.plug( RemoteCallbacks.plug(
callbacksOptions: fetchOptions.ref.callbacks, callbacksOptions: fetchOptions.ref.callbacks,
callbacks: callbacks, callbacks: callbacks,
@ -271,20 +203,13 @@ String getNamespace(Pointer<git_repository> repo) {
/// ///
/// The [namespace] should not include the refs folder, e.g. to namespace all references /// The [namespace] should not include the refs folder, e.g. to namespace all references
/// under refs/namespaces/foo/, use foo as the namespace. /// under refs/namespaces/foo/, use foo as the namespace.
///
/// Throws a [LibGit2Error] if error occured.
void setNamespace({ void setNamespace({
required Pointer<git_repository> repoPointer, required Pointer<git_repository> repoPointer,
String? namespace, String? namespace,
}) { }) {
final nmspace = namespace?.toNativeUtf8().cast<Int8>() ?? nullptr; final nmspace = namespace?.toNativeUtf8().cast<Int8>() ?? nullptr;
final error = libgit2.git_repository_set_namespace(repoPointer, nmspace); libgit2.git_repository_set_namespace(repoPointer, nmspace);
calloc.free(nmspace); calloc.free(nmspace);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
} }
/// Check if a repository is bare or not. /// Check if a repository is bare or not.
@ -401,19 +326,11 @@ Map<String, String> identity(Pointer<git_repository> repo) {
/// will be returned, including global and system configurations (if they are available). /// will be returned, including global and system configurations (if they are available).
/// ///
/// The configuration file must be freed once it's no longer being used by the user. /// The configuration file must be freed once it's no longer being used by the user.
///
/// Throws a [LibGit2Error] if error occured.
Pointer<git_config> config(Pointer<git_repository> repo) { Pointer<git_config> config(Pointer<git_repository> repo) {
final out = calloc<Pointer<git_config>>(); final out = calloc<Pointer<git_config>>();
final error = libgit2.git_repository_config(out, repo); libgit2.git_repository_config(out, repo);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value; return out.value;
} }
}
/// Get a snapshot of the repository's configuration. /// Get a snapshot of the repository's configuration.
/// ///
@ -421,19 +338,11 @@ Pointer<git_config> config(Pointer<git_repository> repo) {
/// The contents of this snapshot will not change, even if the underlying config files are modified. /// The contents of this snapshot will not change, even if the underlying config files are modified.
/// ///
/// The configuration file must be freed once it's no longer being used by the user. /// The configuration file must be freed once it's no longer being used by the user.
///
/// Throws a [LibGit2Error] if error occured.
Pointer<git_config> configSnapshot(Pointer<git_repository> repo) { Pointer<git_config> configSnapshot(Pointer<git_repository> repo) {
final out = calloc<Pointer<git_config>>(); final out = calloc<Pointer<git_config>>();
final error = libgit2.git_repository_config_snapshot(out, repo); libgit2.git_repository_config_snapshot(out, repo);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value; return out.value;
} }
}
/// Get the Index file for this repository. /// Get the Index file for this repository.
/// ///
@ -441,19 +350,11 @@ Pointer<git_config> configSnapshot(Pointer<git_repository> repo) {
/// will be returned (the one located in `.git/index`). /// will be returned (the one located in `.git/index`).
/// ///
/// The index must be freed once it's no longer being used. /// The index must be freed once it's no longer being used.
///
/// Throws a [LibGit2Error] if error occured.
Pointer<git_index> index(Pointer<git_repository> repo) { Pointer<git_index> index(Pointer<git_repository> repo) {
final out = calloc<Pointer<git_index>>(); final out = calloc<Pointer<git_index>>();
final error = libgit2.git_repository_index(out, repo); libgit2.git_repository_index(out, repo);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value; return out.value;
} }
}
/// Determine if the repository was a shallow clone. /// Determine if the repository was a shallow clone.
bool isShallow(Pointer<git_repository> repo) { bool isShallow(Pointer<git_repository> repo) {
@ -585,27 +486,6 @@ void setHeadDetached({
} }
} }
/// Make the repository HEAD directly point to the commit.
///
/// This behaves like [setHeadDetached] but takes an annotated commit,
/// which lets you specify which extended sha syntax string was specified
/// by a user, allowing for more exact reflog messages.
///
/// See the documentation for [setHeadDetached].
void setHeadDetachedFromAnnotated({
required Pointer<git_repository> repoPointer,
required Pointer<git_annotated_commit> commitishPointer,
}) {
final error = libgit2.git_repository_set_head_detached_from_annotated(
repoPointer,
commitishPointer,
);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
}
/// Set the path to the working directory for this repository. /// Set the path to the working directory for this repository.
/// ///
/// The working directory doesn't need to be the same one that contains the /// The working directory doesn't need to be the same one that contains the
@ -665,24 +545,5 @@ String workdir(Pointer<git_repository> repo) {
} }
} }
/// Create a "fake" repository to wrap an object database
///
/// Create a repository object to wrap an object database to be used with the API
/// when all you have is an object database. This doesn't have any paths associated
/// with it, so use with care.
///
/// Throws a [LibGit2Error] if error occured.
Pointer<git_repository> wrapODB(Pointer<git_odb> odb) {
final out = calloc<Pointer<git_repository>>();
final error = libgit2.git_repository_wrap_odb(out, odb);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value;
}
}
/// Free a previously allocated repository. /// Free a previously allocated repository.
void free(Pointer<git_repository> repo) => libgit2.git_repository_free(repo); void free(Pointer<git_repository> repo) => libgit2.git_repository_free(repo);

View file

@ -1,5 +1,4 @@
import 'dart:ffi'; import 'dart:ffi';
import '../error.dart';
import 'libgit2_bindings.dart'; import 'libgit2_bindings.dart';
import '../util.dart'; import '../util.dart';
@ -13,22 +12,11 @@ import '../util.dart';
/// ///
/// HARD reset will trigger a MIXED reset and the working directory will be replaced /// HARD reset will trigger a MIXED reset and the working directory will be replaced
/// with the content of the index. (Untracked and ignored files will be left alone, however.) /// with the content of the index. (Untracked and ignored files will be left alone, however.)
///
/// Throws a [LibGit2Error] if error occured.
void reset({ void reset({
required Pointer<git_repository> repoPointer, required Pointer<git_repository> repoPointer,
required Pointer<git_object> targetPointer, required Pointer<git_object> targetPointer,
required int resetType, required int resetType,
required Pointer<git_checkout_options> checkoutOptsPointer, required Pointer<git_checkout_options> checkoutOptsPointer,
}) { }) {
final error = libgit2.git_reset( libgit2.git_reset(repoPointer, targetPointer, resetType, checkoutOptsPointer);
repoPointer,
targetPointer,
resetType,
checkoutOptsPointer,
);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
} }

View file

@ -32,17 +32,11 @@ Pointer<git_revwalk> create(Pointer<git_repository> repo) {
/// Change the sorting mode when iterating through the repository's contents. /// Change the sorting mode when iterating through the repository's contents.
/// ///
/// Changing the sorting mode resets the walker. /// Changing the sorting mode resets the walker.
///
/// Throws a [LibGit2Error] if error occured.
void sorting({ void sorting({
required Pointer<git_revwalk> walkerPointer, required Pointer<git_revwalk> walkerPointer,
required int sortMode, required int sortMode,
}) { }) {
final error = libgit2.git_revwalk_sorting(walkerPointer, sortMode); libgit2.git_revwalk_sorting(walkerPointer, sortMode);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
} }
/// Add a new root for the traversal. /// Add a new root for the traversal.
@ -130,14 +124,8 @@ void reset(Pointer<git_revwalk> walker) => libgit2.git_revwalk_reset(walker);
/// Simplify the history by first-parent. /// Simplify the history by first-parent.
/// ///
/// No parents other than the first for each commit will be enqueued. /// No parents other than the first for each commit will be enqueued.
///
/// Throws a [LibGit2Error] if error occured.
void simplifyFirstParent(Pointer<git_revwalk> walker) { void simplifyFirstParent(Pointer<git_revwalk> walker) {
final error = libgit2.git_revwalk_simplify_first_parent(walker); libgit2.git_revwalk_simplify_first_parent(walker);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
} }
/// Return the repository on which this walker is operating. /// Return the repository on which this walker is operating.

View file

@ -56,19 +56,11 @@ Pointer<git_signature> now({required String name, required String email}) {
/// ///
/// This looks up the user.name and user.email from the configuration and uses the /// This looks up the user.name and user.email from the configuration and uses the
/// current time as the timestamp, and creates a new signature based on that information. /// current time as the timestamp, and creates a new signature based on that information.
///
/// Throws a [LibGit2Error] if error occured.
Pointer<git_signature> defaultSignature(Pointer<git_repository> repo) { Pointer<git_signature> defaultSignature(Pointer<git_repository> repo) {
final out = calloc<Pointer<git_signature>>(); final out = calloc<Pointer<git_signature>>();
final error = libgit2.git_signature_default(out, repo); libgit2.git_signature_default(out, repo);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out.value; return out.value;
} }
}
/// Free an existing signature. /// Free an existing signature.
void free(Pointer<git_signature> sig) => libgit2.git_signature_free(sig); void free(Pointer<git_signature> sig) => libgit2.git_signature_free(sig);

View file

@ -48,16 +48,11 @@ void apply({
List<String>? paths, List<String>? paths,
}) { }) {
final options = calloc<git_stash_apply_options>(); final options = calloc<git_stash_apply_options>();
final optionsError = libgit2.git_stash_apply_options_init( libgit2.git_stash_apply_options_init(
options, options,
GIT_STASH_APPLY_OPTIONS_VERSION, GIT_STASH_APPLY_OPTIONS_VERSION,
); );
if (optionsError < 0) {
calloc.free(options);
throw LibGit2Error(libgit2.git_error_last());
}
final checkoutOptions = checkout_bindings.initOptions( final checkoutOptions = checkout_bindings.initOptions(
strategy: strategy, strategy: strategy,
directory: directory, directory: directory,
@ -88,7 +83,11 @@ void apply({
/// ///
/// Throws a [LibGit2Error] if error occured. /// Throws a [LibGit2Error] if error occured.
void drop({required Pointer<git_repository> repoPointer, required int index}) { void drop({required Pointer<git_repository> repoPointer, required int index}) {
libgit2.git_stash_drop(repoPointer, index); final error = libgit2.git_stash_drop(repoPointer, index);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
} }
/// Apply a single stashed state from the stash list and remove it from the list if successful. /// Apply a single stashed state from the stash list and remove it from the list if successful.
@ -103,16 +102,11 @@ void pop({
List<String>? paths, List<String>? paths,
}) { }) {
final options = calloc<git_stash_apply_options>(); final options = calloc<git_stash_apply_options>();
final optionsError = libgit2.git_stash_apply_options_init( libgit2.git_stash_apply_options_init(
options, options,
GIT_STASH_APPLY_OPTIONS_VERSION, GIT_STASH_APPLY_OPTIONS_VERSION,
); );
if (optionsError < 0) {
calloc.free(options);
throw LibGit2Error(libgit2.git_error_last());
}
final checkoutOptions = checkout_bindings.initOptions( final checkoutOptions = checkout_bindings.initOptions(
strategy: strategy, strategy: strategy,
directory: directory, directory: directory,

View file

@ -31,19 +31,11 @@ int listEntryCount(Pointer<git_status_list> statuslist) {
/// Get a pointer to one of the entries in the status list. /// Get a pointer to one of the entries in the status list.
/// ///
/// The entry is not modifiable and should not be freed. /// The entry is not modifiable and should not be freed.
///
/// Throws [RangeError] if position is out of bounds
Pointer<git_status_entry> getByIndex({ Pointer<git_status_entry> getByIndex({
required Pointer<git_status_list> statuslistPointer, required Pointer<git_status_list> statuslistPointer,
required int index, required int index,
}) { }) {
final result = libgit2.git_status_byindex(statuslistPointer, index); return libgit2.git_status_byindex(statuslistPointer, index);
if (result == nullptr) {
throw RangeError('Out of bounds');
} else {
return result;
}
} }
/// Get file status for a single file. /// Get file status for a single file.

View file

@ -22,25 +22,18 @@ int _listCb(
} }
/// Returns a list with all tracked submodules paths of a repository. /// Returns a list with all tracked submodules paths of a repository.
///
/// Throws a [LibGit2Error] if error occured.
List<String> list(Pointer<git_repository> repo) { List<String> list(Pointer<git_repository> repo) {
const except = -1; const except = -1;
final callback = Pointer.fromFunction< final callback = Pointer.fromFunction<
Int32 Function(Pointer<git_submodule>, Pointer<Int8>, Pointer<Void>)>( Int32 Function(Pointer<git_submodule>, Pointer<Int8>, Pointer<Void>)>(
_listCb, except); _listCb, except);
final error = libgit2.git_submodule_foreach(repo, callback, nullptr); libgit2.git_submodule_foreach(repo, callback, nullptr);
if (error < 0) {
_pathsList.clear();
throw LibGit2Error(libgit2.git_error_last());
} else {
final result = _pathsList.toList(growable: false); final result = _pathsList.toList(growable: false);
_pathsList.clear(); _pathsList.clear();
return result; return result;
} }
}
/// Lookup submodule information by name or path. /// Lookup submodule information by name or path.
/// ///
@ -76,18 +69,12 @@ Pointer<git_submodule> lookup({
/// ///
/// By default, existing entries will not be overwritten, but setting [overwrite] /// By default, existing entries will not be overwritten, but setting [overwrite]
/// to true forces them to be updated. /// to true forces them to be updated.
///
/// Throws a [LibGit2Error] if error occured.
void init({ void init({
required Pointer<git_submodule> submodulePointer, required Pointer<git_submodule> submodulePointer,
bool overwrite = false, bool overwrite = false,
}) { }) {
final overwriteC = overwrite ? 1 : 0; final overwriteC = overwrite ? 1 : 0;
final error = libgit2.git_submodule_init(submodulePointer, overwriteC); libgit2.git_submodule_init(submodulePointer, overwriteC);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
} }
/// Update a submodule. This will clone a missing submodule and checkout the /// Update a submodule. This will clone a missing submodule and checkout the
@ -108,16 +95,11 @@ void update({
}) { }) {
final initC = init ? 1 : 0; final initC = init ? 1 : 0;
final options = calloc<git_submodule_update_options>(); final options = calloc<git_submodule_update_options>();
final optionsError = libgit2.git_submodule_update_options_init( libgit2.git_submodule_update_options_init(
options, options,
GIT_SUBMODULE_UPDATE_OPTIONS_VERSION, GIT_SUBMODULE_UPDATE_OPTIONS_VERSION,
); );
if (optionsError < 0) {
calloc.free(options);
throw LibGit2Error(libgit2.git_error_last());
}
RemoteCallbacks.plug( RemoteCallbacks.plug(
callbacksOptions: options.ref.fetch_opts.callbacks, callbacksOptions: options.ref.fetch_opts.callbacks,
callbacks: callbacks, callbacks: callbacks,
@ -199,17 +181,11 @@ void clone({
}) { }) {
final out = calloc<Pointer<git_repository>>(); final out = calloc<Pointer<git_repository>>();
final options = calloc<git_submodule_update_options>(); final options = calloc<git_submodule_update_options>();
final optionsError = libgit2.git_submodule_update_options_init( libgit2.git_submodule_update_options_init(
options, options,
GIT_SUBMODULE_UPDATE_OPTIONS_VERSION, GIT_SUBMODULE_UPDATE_OPTIONS_VERSION,
); );
if (optionsError < 0) {
calloc.free(out);
calloc.free(options);
throw LibGit2Error(libgit2.git_error_last());
}
RemoteCallbacks.plug( RemoteCallbacks.plug(
callbacksOptions: options.ref.fetch_opts.callbacks, callbacksOptions: options.ref.fetch_opts.callbacks,
callbacks: callbacks, callbacks: callbacks,
@ -232,22 +208,14 @@ void clone({
/// the clone of the submodule. This adds the `.gitmodules` file and the newly /// the clone of the submodule. This adds the `.gitmodules` file and the newly
/// cloned submodule to the index to be ready to be committed (but doesn't actually /// cloned submodule to the index to be ready to be committed (but doesn't actually
/// do the commit). /// do the commit).
///
/// Throws a [LibGit2Error] if error occured.
void addFinalize(Pointer<git_submodule> submodule) { void addFinalize(Pointer<git_submodule> submodule) {
final error = libgit2.git_submodule_add_finalize(submodule); libgit2.git_submodule_add_finalize(submodule);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
} }
/// Get the status for a submodule. /// Get the status for a submodule.
/// ///
/// This looks at a submodule and tries to determine the status. How deeply it examines /// This looks at a submodule and tries to determine the status. How deeply it examines
/// the working directory to do this will depend on the [ignore] value. /// the working directory to do this will depend on the [ignore] value.
///
/// Throws a [LibGit2Error] if error occured.
int status({ int status({
required Pointer<git_repository> repoPointer, required Pointer<git_repository> repoPointer,
required String name, required String name,
@ -255,19 +223,14 @@ int status({
}) { }) {
final out = calloc<Uint32>(); final out = calloc<Uint32>();
final nameC = name.toNativeUtf8().cast<Int8>(); final nameC = name.toNativeUtf8().cast<Int8>();
final error = libgit2.git_submodule_status(out, repoPointer, nameC, ignore); libgit2.git_submodule_status(out, repoPointer, nameC, ignore);
calloc.free(nameC); calloc.free(nameC);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
final result = out.value; final result = out.value;
calloc.free(out); calloc.free(out);
return result; return result;
} }
}
/// Copy submodule remote info into submodule repo. /// Copy submodule remote info into submodule repo.
/// ///
@ -275,15 +238,8 @@ int status({
/// config, acting like `git submodule sync`. This is useful if you have altered the URL /// config, acting like `git submodule sync`. This is useful if you have altered the URL
/// for the submodule (or it has been altered by a fetch of upstream changes) and you /// for the submodule (or it has been altered by a fetch of upstream changes) and you
/// need to update your local repo. /// need to update your local repo.
/// void sync(Pointer<git_submodule> submodule) =>
/// Throws a [LibGit2Error] if error occured. libgit2.git_submodule_sync(submodule);
void sync(Pointer<git_submodule> submodule) {
final error = libgit2.git_submodule_sync(submodule);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
}
/// Reread submodule info from config, index, and HEAD. /// Reread submodule info from config, index, and HEAD.
/// ///
@ -296,11 +252,7 @@ void reload({
bool force = false, bool force = false,
}) { }) {
final forceC = force ? 1 : 0; final forceC = force ? 1 : 0;
final error = libgit2.git_submodule_reload(submodulePointer, forceC); libgit2.git_submodule_reload(submodulePointer, forceC);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
} }
/// Get the name of submodule. /// Get the name of submodule.
@ -325,8 +277,6 @@ String url(Pointer<git_submodule> submodule) {
/// ///
/// After calling this, you may wish to call [sync] to write the changes to /// After calling this, you may wish to call [sync] to write the changes to
/// the checked out submodule repository. /// the checked out submodule repository.
///
/// Throws a [LibGit2Error] if error occured.
void setUrl({ void setUrl({
required Pointer<git_repository> repoPointer, required Pointer<git_repository> repoPointer,
required String name, required String name,
@ -335,14 +285,10 @@ void setUrl({
final nameC = name.toNativeUtf8().cast<Int8>(); final nameC = name.toNativeUtf8().cast<Int8>();
final urlC = url.toNativeUtf8().cast<Int8>(); final urlC = url.toNativeUtf8().cast<Int8>();
final error = libgit2.git_submodule_set_url(repoPointer, nameC, urlC); libgit2.git_submodule_set_url(repoPointer, nameC, urlC);
calloc.free(nameC); calloc.free(nameC);
calloc.free(urlC); calloc.free(urlC);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
} }
/// Get the branch for the submodule. /// Get the branch for the submodule.
@ -355,8 +301,6 @@ String branch(Pointer<git_submodule> submodule) {
/// ///
/// After calling this, you may wish to call [sync] to write the changes to /// After calling this, you may wish to call [sync] to write the changes to
/// the checked out submodule repository. /// the checked out submodule repository.
///
/// Throws a [LibGit2Error] if error occured.
void setBranch({ void setBranch({
required Pointer<git_repository> repoPointer, required Pointer<git_repository> repoPointer,
required String name, required String name,
@ -365,14 +309,10 @@ void setBranch({
final nameC = name.toNativeUtf8().cast<Int8>(); final nameC = name.toNativeUtf8().cast<Int8>();
final branchC = branch.toNativeUtf8().cast<Int8>(); final branchC = branch.toNativeUtf8().cast<Int8>();
final error = libgit2.git_submodule_set_branch(repoPointer, nameC, branchC); libgit2.git_submodule_set_branch(repoPointer, nameC, branchC);
calloc.free(nameC); calloc.free(nameC);
calloc.free(branchC); calloc.free(branchC);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
} }
/// Get the OID for the submodule in the current HEAD tree. /// Get the OID for the submodule in the current HEAD tree.
@ -412,21 +352,14 @@ int ignore(Pointer<git_submodule> submodule) {
/// Set the ignore rule for the submodule in the configuration. /// Set the ignore rule for the submodule in the configuration.
/// ///
/// This does not affect any currently-loaded instances. /// This does not affect any currently-loaded instances.
///
/// Throws a [LibGit2Error] if error occured.
void setIgnore({ void setIgnore({
required Pointer<git_repository> repoPointer, required Pointer<git_repository> repoPointer,
required String name, required String name,
required int ignore, required int ignore,
}) { }) {
final nameC = name.toNativeUtf8().cast<Int8>(); final nameC = name.toNativeUtf8().cast<Int8>();
final error = libgit2.git_submodule_set_ignore(repoPointer, nameC, ignore); libgit2.git_submodule_set_ignore(repoPointer, nameC, ignore);
calloc.free(nameC); calloc.free(nameC);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
} }
/// Get the update rule that will be used for the submodule. /// Get the update rule that will be used for the submodule.
@ -439,21 +372,14 @@ int updateRule(Pointer<git_submodule> submodule) {
/// Set the update rule for the submodule in the configuration. /// Set the update rule for the submodule in the configuration.
/// ///
/// This setting won't affect any existing instances. /// This setting won't affect any existing instances.
///
/// Throws a [LibGit2Error] if error occured.
void setUpdateRule({ void setUpdateRule({
required Pointer<git_repository> repoPointer, required Pointer<git_repository> repoPointer,
required String name, required String name,
required int update, required int update,
}) { }) {
final nameC = name.toNativeUtf8().cast<Int8>(); final nameC = name.toNativeUtf8().cast<Int8>();
final error = libgit2.git_submodule_set_update(repoPointer, nameC, update); libgit2.git_submodule_set_update(repoPointer, nameC, update);
calloc.free(nameC); calloc.free(nameC);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
} }
/// Get the containing repository for a submodule. /// Get the containing repository for a submodule.

View file

@ -142,10 +142,5 @@ void delete({
} }
} }
/// Get the repository that contains the tag.
Pointer<git_repository> owner(Pointer<git_tag> tag) {
return libgit2.git_tag_owner(tag);
}
/// Close an open tag to release memory. /// Close an open tag to release memory.
void free(Pointer<git_tag> tag) => libgit2.git_tag_free(tag); void free(Pointer<git_tag> tag) => libgit2.git_tag_free(tag);

View file

@ -109,16 +109,6 @@ String entryName(Pointer<git_tree_entry> entry) =>
int entryFilemode(Pointer<git_tree_entry> entry) => int entryFilemode(Pointer<git_tree_entry> entry) =>
libgit2.git_tree_entry_filemode(entry); libgit2.git_tree_entry_filemode(entry);
/// Compare two tree entries.
///
/// Returns <0 if e1 is before e2, 0 if e1 == e2, >0 if e1 is after e2.
int compare({
required Pointer<git_tree_entry> aPointer,
required Pointer<git_tree_entry> bPointer,
}) {
return libgit2.git_tree_entry_cmp(aPointer, bPointer);
}
/// Free a user-owned tree entry. /// Free a user-owned tree entry.
/// ///
/// IMPORTANT: This function is only needed for tree entries owned by the user, /// IMPORTANT: This function is only needed for tree entries owned by the user,

View file

@ -32,30 +32,14 @@ Pointer<git_treebuilder> create({
} }
/// Write the contents of the tree builder as a tree object. /// Write the contents of the tree builder as a tree object.
///
/// Throws a [LibGit2Error] if error occured.
Pointer<git_oid> write(Pointer<git_treebuilder> bld) { Pointer<git_oid> write(Pointer<git_treebuilder> bld) {
final out = calloc<git_oid>(); final out = calloc<git_oid>();
final error = libgit2.git_treebuilder_write(out, bld); libgit2.git_treebuilder_write(out, bld);
if (error < 0) {
calloc.free(out);
throw LibGit2Error(libgit2.git_error_last());
} else {
return out; return out;
} }
}
/// Clear all the entires in the builder. /// Clear all the entires in the builder.
/// void clear(Pointer<git_treebuilder> bld) => libgit2.git_treebuilder_clear(bld);
/// Throws a [LibGit2Error] if error occured.
void clear(Pointer<git_treebuilder> bld) {
final error = libgit2.git_treebuilder_clear(bld);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
}
/// Get the number of entries listed in a treebuilder. /// Get the number of entries listed in a treebuilder.
int entryCount(Pointer<git_treebuilder> bld) => int entryCount(Pointer<git_treebuilder> bld) =>

View file

@ -22,18 +22,7 @@ Pointer<git_worktree> create({
final pathC = path.toNativeUtf8().cast<Int8>(); final pathC = path.toNativeUtf8().cast<Int8>();
final opts = calloc<git_worktree_add_options>(); final opts = calloc<git_worktree_add_options>();
final optsError = libgit2.git_worktree_add_options_init( libgit2.git_worktree_add_options_init(opts, GIT_WORKTREE_ADD_OPTIONS_VERSION);
opts,
GIT_WORKTREE_ADD_OPTIONS_VERSION,
);
if (optsError < 0) {
calloc.free(out);
calloc.free(nameC);
calloc.free(pathC);
calloc.free(opts);
throw LibGit2Error(libgit2.git_error_last());
}
opts.ref.ref = nullptr; opts.ref.ref = nullptr;
if (refPointer != null) { if (refPointer != null) {
@ -84,29 +73,19 @@ Pointer<git_worktree> lookup({
/// Throws a [LibGit2Error] if error occured. /// Throws a [LibGit2Error] if error occured.
bool isPrunable(Pointer<git_worktree> wt) { bool isPrunable(Pointer<git_worktree> wt) {
final opts = calloc<git_worktree_prune_options>(); final opts = calloc<git_worktree_prune_options>();
final optsError = libgit2.git_worktree_prune_options_init( libgit2.git_worktree_prune_options_init(
opts, opts,
GIT_WORKTREE_PRUNE_OPTIONS_VERSION, GIT_WORKTREE_PRUNE_OPTIONS_VERSION,
); );
if (optsError < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
return libgit2.git_worktree_is_prunable(wt, opts) > 0 ? true : false; return libgit2.git_worktree_is_prunable(wt, opts) > 0 ? true : false;
} }
/// Prune working tree. /// Prune working tree.
/// ///
/// Prune the working tree, that is remove the git data structures on disk. /// Prune the working tree, that is remove the git data structures on disk.
///
/// Throws a [LibGit2Error] if error occured.
void prune(Pointer<git_worktree> wt) { void prune(Pointer<git_worktree> wt) {
final error = libgit2.git_worktree_prune(wt, nullptr); libgit2.git_worktree_prune(wt, nullptr);
if (error < 0) {
throw LibGit2Error(libgit2.git_error_last());
}
} }
/// List names of linked working trees. /// List names of linked working trees.
@ -143,18 +122,8 @@ String path(Pointer<git_worktree> wt) {
/// ///
/// A worktree may be locked if the linked working tree is stored on a portable /// A worktree may be locked if the linked working tree is stored on a portable
/// device which is not available. /// device which is not available.
///
/// Throws a [LibGit2Error] if error occured.
bool isLocked(Pointer<git_worktree> wt) { bool isLocked(Pointer<git_worktree> wt) {
final result = libgit2.git_worktree_is_locked(nullptr, wt); return libgit2.git_worktree_is_locked(nullptr, wt) == 1 ? true : false;
if (result < 0) {
throw LibGit2Error(libgit2.git_error_last());
} else if (result == 0) {
return false;
} else {
return true;
}
} }
/// Lock worktree if not already locked. /// Lock worktree if not already locked.

View file

@ -90,7 +90,7 @@ class Blob {
final result = patch_bindings.fromBlobs( final result = patch_bindings.fromBlobs(
oldBlobPointer: _blobPointer, oldBlobPointer: _blobPointer,
oldAsPath: oldAsPath, oldAsPath: oldAsPath,
newBlobPointer: newBlob?.pointer, newBlobPointer: newBlob?.pointer ?? nullptr,
newAsPath: newAsPath, newAsPath: newAsPath,
flags: flags.fold(0, (acc, e) => acc | e.value), flags: flags.fold(0, (acc, e) => acc | e.value),
contextLines: contextLines, contextLines: contextLines,

View file

@ -37,29 +37,26 @@ class Branch {
); );
} }
/// Lookups a branch by its [name] in a [repo]sitory. /// Lookups a branch by its [name] and [type] in a [repo]sitory.
/// ///
/// The branch name will be checked for validity. /// The branch name will be checked for validity.
/// ///
/// Should be freed with [free] to release allocated memory when no longer /// If branch [type] is [GitBranch.remote] you must include the remote name
/// needed. /// in the [name] (e.g. "origin/master").
///
/// Should be freed to release allocated memory when no longer needed.
/// ///
/// Throws a [LibGit2Error] if error occured. /// Throws a [LibGit2Error] if error occured.
Branch.lookup({required Repository repo, required String name}) { Branch.lookup({
final ref = Reference( required Repository repo,
reference_bindings.lookupDWIM( required String name,
repoPointer: repo.pointer, GitBranch type = GitBranch.local,
name: name, }) {
),
);
_branchPointer = bindings.lookup( _branchPointer = bindings.lookup(
repoPointer: repo.pointer, repoPointer: repo.pointer,
branchName: name, branchName: name,
branchType: ref.isBranch ? GitBranch.local.value : GitBranch.remote.value, branchType: type.value,
); );
ref.free();
} }
late final Pointer<git_reference> _branchPointer; late final Pointer<git_reference> _branchPointer;

View file

@ -80,8 +80,6 @@ class Commit {
Signature get author => Signature(bindings.author(_commitPointer)); Signature get author => Signature(bindings.author(_commitPointer));
/// Returns list of parent commits [Oid]s. /// Returns list of parent commits [Oid]s.
///
/// Throws a [LibGit2Error] if error occured.
List<Oid> get parents { List<Oid> get parents {
var parents = <Oid>[]; var parents = <Oid>[];
final parentCount = bindings.parentCount(_commitPointer); final parentCount = bindings.parentCount(_commitPointer);
@ -114,3 +112,29 @@ class Commit {
'time: $time, committer: $committer, author: $author}'; 'time: $time, committer: $committer, author: $author}';
} }
} }
/// An annotated commit contains information about how it was looked up, which may be useful
/// for functions like merge or rebase to provide context to the operation. For example, conflict
/// files will include the name of the source or target branches being merged.
///
/// Note: for internal use.
class AnnotatedCommit {
/// Lookups an annotated commit from the given commit [oid]. The resulting annotated commit
/// must be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
AnnotatedCommit.lookup({required Repository repo, required Oid oid}) {
_annotatedCommitPointer = bindings.annotatedLookup(
repoPointer: repo.pointer,
oidPointer: oid.pointer,
);
}
late final Pointer<Pointer<git_annotated_commit>> _annotatedCommitPointer;
/// Pointer to pointer to memory address for allocated commit object.
Pointer<Pointer<git_annotated_commit>> get pointer => _annotatedCommitPointer;
/// Releases memory allocated for commit object.
void free() => bindings.annotatedFree(_annotatedCommitPointer.value);
}

View file

@ -13,6 +13,15 @@ class Diff {
/// Should be freed with `free()` to release allocated memory. /// Should be freed with `free()` to release allocated memory.
Diff(this._diffPointer); Diff(this._diffPointer);
/// Reads the contents of a git patch file into a git diff object.
///
/// The diff object produced is similar to the one that would be produced if you actually
/// produced it computationally by comparing two trees, however there may be subtle differences.
/// For example, a patch file likely contains abbreviated object IDs, so the object IDs in a
/// diff delta produced by this function will also be abbreviated.
///
/// This function will only read patch files created by a git implementation, it will not
/// read unified diffs produced by the `diff` program, nor any other types of patch files.
Diff.parse(String content) { Diff.parse(String content) {
libgit2.git_libgit2_init(); libgit2.git_libgit2_init();
_diffPointer = bindings.parse(content); _diffPointer = bindings.parse(content);
@ -63,7 +72,9 @@ class Diff {
patch.free(); patch.free();
} }
final result = buffer.ref.ptr.cast<Utf8>().toDartString(); final result = buffer.ref.ptr == nullptr
? ''
: buffer.ref.ptr.cast<Utf8>().toDartString();
calloc.free(buffer); calloc.free(buffer);
return result; return result;
} }
@ -115,7 +126,7 @@ class Diff {
/// and should in fact generate the same IDs as the upstream git project does. /// and should in fact generate the same IDs as the upstream git project does.
/// ///
/// Throws a [LibGit2Error] if error occured. /// Throws a [LibGit2Error] if error occured.
Oid get patchId => Oid(bindings.patchId(_diffPointer)); Oid get patchOid => Oid(bindings.patchOid(_diffPointer));
/// Releases memory allocated for diff object. /// Releases memory allocated for diff object.
void free() => bindings.free(_diffPointer); void free() => bindings.free(_diffPointer);
@ -301,8 +312,6 @@ class DiffHunk {
} }
/// Returns list of lines in a hunk of a patch. /// Returns list of lines in a hunk of a patch.
///
/// Throws a [LibGit2Error] if error occured.
List<DiffLine> get lines { List<DiffLine> get lines {
var lines = <DiffLine>[]; var lines = <DiffLine>[];
for (var i = 0; i < linesCount; i++) { for (var i = 0; i < linesCount; i++) {

View file

@ -131,8 +131,6 @@ class Index with IterableMixin<IndexEntry> {
/// if it has changed since the last time it was loaded. Purely in-memory index data /// if it has changed since the last time it was loaded. Purely in-memory index data
/// will be untouched. Be aware: if there are changes on disk, unwritten in-memory changes /// will be untouched. Be aware: if there are changes on disk, unwritten in-memory changes
/// are discarded. /// are discarded.
///
/// Throws a [LibGit2Error] if error occured.
void read({bool force = true}) => void read({bool force = true}) =>
bindings.read(indexPointer: _indexPointer, force: force); bindings.read(indexPointer: _indexPointer, force: force);
@ -143,8 +141,6 @@ class Index with IterableMixin<IndexEntry> {
} }
/// Writes an existing index object from memory back to disk using an atomic file lock. /// Writes an existing index object from memory back to disk using an atomic file lock.
///
/// Throws a [LibGit2Error] if error occured.
void write() => bindings.write(_indexPointer); void write() => bindings.write(_indexPointer);
/// Writes the index as a tree. /// Writes the index as a tree.
@ -180,8 +176,6 @@ class Index with IterableMixin<IndexEntry> {
bindings.removeAll(indexPointer: _indexPointer, pathspec: path); bindings.removeAll(indexPointer: _indexPointer, pathspec: path);
/// Creates a diff between the repository index and the workdir directory. /// Creates a diff between the repository index and the workdir directory.
///
/// Throws a [LibGit2Error] if error occured.
Diff diffToWorkdir({ Diff diffToWorkdir({
Set<GitDiff> flags = const {GitDiff.normal}, Set<GitDiff> flags = const {GitDiff.normal},
int contextLines = 3, int contextLines = 3,
@ -197,8 +191,6 @@ class Index with IterableMixin<IndexEntry> {
} }
/// Creates a diff between a tree and repository index. /// Creates a diff between a tree and repository index.
///
/// Throws a [LibGit2Error] if error occured.
Diff diffToTree({ Diff diffToTree({
required Tree tree, required Tree tree,
Set<GitDiff> flags = const {GitDiff.normal}, Set<GitDiff> flags = const {GitDiff.normal},

View file

@ -9,8 +9,6 @@ class Mailmap {
/// ///
/// This object is empty, so you'll have to add a mailmap file before you can /// This object is empty, so you'll have to add a mailmap file before you can
/// do anything with it. Must be freed with `free()`. /// do anything with it. Must be freed with `free()`.
///
/// Throws a [LibGit2Error] if error occured.
Mailmap.empty() { Mailmap.empty() {
libgit2.git_libgit2_init(); libgit2.git_libgit2_init();
@ -20,8 +18,6 @@ class Mailmap {
/// Initializes a new instance of [Mailmap] class from provided buffer. /// Initializes a new instance of [Mailmap] class from provided buffer.
/// ///
/// Must be freed with `free()`. /// Must be freed with `free()`.
///
/// Throws a [LibGit2Error] if error occured.
Mailmap.fromBuffer(String buffer) { Mailmap.fromBuffer(String buffer) {
libgit2.git_libgit2_init(); libgit2.git_libgit2_init();
@ -50,8 +46,6 @@ class Mailmap {
/// Returns list containing resolved [name] and [email] to the corresponding real name /// Returns list containing resolved [name] and [email] to the corresponding real name
/// and real email respectively. /// and real email respectively.
///
/// Throws a [LibGit2Error] if error occured.
List<String> resolve({ List<String> resolve({
required String name, required String name,
required String email, required String email,
@ -64,8 +58,6 @@ class Mailmap {
} }
/// Resolves a signature to use real names and emails with a mailmap. /// Resolves a signature to use real names and emails with a mailmap.
///
/// Throws a [LibGit2Error] if error occured.
Signature resolveSignature(Signature signature) { Signature resolveSignature(Signature signature) {
return Signature(bindings.resolveSignature( return Signature(bindings.resolveSignature(
mailmapPointer: _mailmapPointer, mailmapPointer: _mailmapPointer,
@ -76,13 +68,16 @@ class Mailmap {
/// Adds a single entry to the given mailmap object. If the entry already exists, /// Adds a single entry to the given mailmap object. If the entry already exists,
/// it will be replaced with the new entry. /// it will be replaced with the new entry.
/// ///
/// Throws a [LibGit2Error] if error occured. /// Throws a [ArgumentError] if [replaceEmail] is empty string.
void addEntry({ void addEntry({
String? realName, String? realName,
String? realEmail, String? realEmail,
String? replaceName, String? replaceName,
required String replaceEmail, required String replaceEmail,
}) { }) {
if (replaceEmail.trim().isEmpty) {
throw ArgumentError.value('replaceEmail can\'t be empty');
} else {
bindings.addEntry( bindings.addEntry(
mailmapPointer: _mailmapPointer, mailmapPointer: _mailmapPointer,
realName: realName, realName: realName,
@ -91,6 +86,7 @@ class Mailmap {
replaceEmail: replaceEmail, replaceEmail: replaceEmail,
); );
} }
}
/// Releases memory allocated for mailmap object. /// Releases memory allocated for mailmap object.
void free() => bindings.free(_mailmapPointer); void free() => bindings.free(_mailmapPointer);

View file

@ -14,8 +14,6 @@ class Odb {
/// ///
/// Before the ODB can be used for read/writing, a custom database backend must be /// Before the ODB can be used for read/writing, a custom database backend must be
/// manually added. /// manually added.
///
/// Throws a [LibGit2Error] if error occured.
Odb.create() { Odb.create() {
libgit2.git_libgit2_init(); libgit2.git_libgit2_init();
@ -36,8 +34,6 @@ class Odb {
/// have been exhausted. /// have been exhausted.
/// ///
/// Writing is disabled on alternate backends. /// Writing is disabled on alternate backends.
///
/// Throws a [LibGit2Error] if error occured.
void addDiskAlternate(String path) { void addDiskAlternate(String path) {
bindings.addDiskAlternate( bindings.addDiskAlternate(
odbPointer: _odbPointer, odbPointer: _odbPointer,

View file

@ -9,7 +9,7 @@ class Patch {
/// Initializes a new instance of [Patch] class from provided /// Initializes a new instance of [Patch] class from provided
/// pointer to patch object in memory and pointers to old and new blobs/buffers. /// pointer to patch object in memory and pointers to old and new blobs/buffers.
/// ///
/// Should be freed with `free()` to release allocated memory. /// Should be freed to release allocated memory.
Patch(this._patchPointer, this._aPointer, this._bPointer); Patch(this._patchPointer, this._aPointer, this._bPointer);
/// Directly generates a patch from the difference between two blobs, buffers or /// Directly generates a patch from the difference between two blobs, buffers or
@ -17,9 +17,7 @@ class Patch {
/// ///
/// [a] and [b] can be [Blob], [String] or null. /// [a] and [b] can be [Blob], [String] or null.
/// ///
/// Should be freed with `free()` to release allocated memory. /// Should be freed to release allocated memory.
///
/// Throws a [LibGit2Error] if error occured.
Patch.create({ Patch.create({
required Object? a, required Object? a,
required Object? b, required Object? b,
@ -35,11 +33,11 @@ class Patch {
var result = <String, Pointer?>{}; var result = <String, Pointer?>{};
if (a is Blob?) { if (a is Blob?) {
if (b is Blob) { if (b is Blob?) {
result = bindings.fromBlobs( result = bindings.fromBlobs(
oldBlobPointer: a?.pointer ?? nullptr, oldBlobPointer: a?.pointer ?? nullptr,
oldAsPath: aPath, oldAsPath: aPath,
newBlobPointer: b.pointer, newBlobPointer: b?.pointer ?? nullptr,
newAsPath: bPath, newAsPath: bPath,
flags: flagsInt, flags: flagsInt,
contextLines: contextLines, contextLines: contextLines,
@ -49,7 +47,7 @@ class Patch {
result = bindings.fromBlobAndBuffer( result = bindings.fromBlobAndBuffer(
oldBlobPointer: a?.pointer, oldBlobPointer: a?.pointer,
oldAsPath: aPath, oldAsPath: aPath,
buffer: b, buffer: b as String?,
bufferAsPath: bPath, bufferAsPath: bPath,
flags: flagsInt, flags: flagsInt,
contextLines: contextLines, contextLines: contextLines,
@ -126,8 +124,6 @@ class Patch {
DiffDelta get delta => DiffDelta(bindings.delta(_patchPointer)); DiffDelta get delta => DiffDelta(bindings.delta(_patchPointer));
/// Returns the list of hunks in a patch. /// Returns the list of hunks in a patch.
///
/// Throws a [LibGit2Error] if error occured.
List<DiffHunk> get hunks { List<DiffHunk> get hunks {
final length = bindings.numHunks(_patchPointer); final length = bindings.numHunks(_patchPointer);
final hunks = <DiffHunk>[]; final hunks = <DiffHunk>[];
@ -157,5 +153,5 @@ class Patch {
} }
@override @override
String toString() => 'Patch{size: $size, delta: $delta}'; String toString() => 'Patch{size: ${size()}, delta: $delta}';
} }

View file

@ -2,7 +2,6 @@ import 'dart:ffi';
import 'package:libgit2dart/libgit2dart.dart'; import 'package:libgit2dart/libgit2dart.dart';
import 'bindings/libgit2_bindings.dart'; import 'bindings/libgit2_bindings.dart';
import 'bindings/rebase.dart' as bindings; import 'bindings/rebase.dart' as bindings;
import 'bindings/commit.dart' as commit_bindings;
class Rebase { class Rebase {
/// Initializes a new instance of the [Rebase] class by initializing a /// Initializes a new instance of the [Rebase] class by initializing a
@ -25,38 +24,33 @@ class Rebase {
Oid? upstream, Oid? upstream,
Oid? onto, Oid? onto,
}) { }) {
Pointer<git_annotated_commit>? _branch, _upstream, _onto; AnnotatedCommit? _branch, _upstream, _onto;
if (branch != null) { if (branch != null) {
_branch = commit_bindings _branch = AnnotatedCommit.lookup(repo: repo, oid: branch);
.annotatedLookup(
repoPointer: repo.pointer,
oidPointer: branch.pointer,
)
.value;
} }
if (upstream != null) { if (upstream != null) {
_upstream = commit_bindings _upstream = AnnotatedCommit.lookup(repo: repo, oid: upstream);
.annotatedLookup(
repoPointer: repo.pointer,
oidPointer: upstream.pointer,
)
.value;
} }
if (onto != null) { if (onto != null) {
_onto = commit_bindings _onto = AnnotatedCommit.lookup(repo: repo, oid: onto);
.annotatedLookup(
repoPointer: repo.pointer,
oidPointer: onto.pointer,
)
.value;
} }
_rebasePointer = bindings.init( _rebasePointer = bindings.init(
repoPointer: repo.pointer, repoPointer: repo.pointer,
branchPointer: _branch, branchPointer: _branch?.pointer.value,
upstreamPointer: _upstream, upstreamPointer: _upstream?.pointer.value,
ontoPointer: _onto, ontoPointer: _onto?.pointer.value,
); );
if (branch != null) {
_branch!.free();
}
if (upstream != null) {
_upstream!.free();
}
if (onto != null) {
_onto!.free();
}
} }
/// Pointer to memory address for allocated rebase object. /// Pointer to memory address for allocated rebase object.
@ -96,14 +90,10 @@ class Rebase {
} }
/// Finishes a rebase that is currently in progress once all patches have been applied. /// Finishes a rebase that is currently in progress once all patches have been applied.
///
/// Throws a [LibGit2Error] if error occured.
void finish() => bindings.finish(_rebasePointer); void finish() => bindings.finish(_rebasePointer);
/// Aborts a rebase that is currently in progress, resetting the repository and working /// Aborts a rebase that is currently in progress, resetting the repository and working
/// directory to their state before rebase began. /// directory to their state before rebase began.
///
/// Throws a [LibGit2Error] if error occured.
void abort() => bindings.abort(_rebasePointer); void abort() => bindings.abort(_rebasePointer);
/// Releases memory allocated for rebase object. /// Releases memory allocated for rebase object.

View file

@ -80,8 +80,6 @@ class Reference {
/// Deletes an existing reference with provided [name]. /// Deletes an existing reference with provided [name].
/// ///
/// This method works for both direct and symbolic references. /// This method works for both direct and symbolic references.
///
/// Throws a [LibGit2Error] if error occured.
static void delete({required Repository repo, required String name}) { static void delete({required Repository repo, required String name}) {
final ref = Reference.lookup(repo: repo, name: name); final ref = Reference.lookup(repo: repo, name: name);
bindings.delete(ref.pointer); bindings.delete(ref.pointer);
@ -226,8 +224,6 @@ class Reference {
String get shorthand => bindings.shorthand(_refPointer); String get shorthand => bindings.shorthand(_refPointer);
/// Checks if a reflog exists for the specified reference [name]. /// Checks if a reflog exists for the specified reference [name].
///
/// Throws a [LibGit2Error] if error occured.
bool get hasLog { bool get hasLog {
return bindings.hasLog( return bindings.hasLog(
repoPointer: bindings.owner(_refPointer), repoPointer: bindings.owner(_refPointer),

View file

@ -6,8 +6,6 @@ import 'bindings/reflog.dart' as bindings;
class RefLog with IterableMixin<RefLogEntry> { class RefLog with IterableMixin<RefLogEntry> {
/// Initializes a new instance of [RefLog] class from provided [Reference]. /// Initializes a new instance of [RefLog] class from provided [Reference].
///
/// Throws a [LibGit2Error] if error occured.
RefLog(Reference ref) { RefLog(Reference ref) {
_reflogPointer = bindings.read( _reflogPointer = bindings.read(
repoPointer: ref.owner.pointer, repoPointer: ref.owner.pointer,

View file

@ -80,8 +80,6 @@ class Remote {
} }
/// Returns a list of the configured remotes for a [repo]sitory. /// Returns a list of the configured remotes for a [repo]sitory.
///
/// Throws a [LibGit2Error] if error occured.
static List<String> list(Repository repo) { static List<String> list(Repository repo) {
return bindings.list(repo.pointer); return bindings.list(repo.pointer);
} }
@ -184,11 +182,19 @@ class Remote {
/// Get the remote's list of push refspecs. /// Get the remote's list of push refspecs.
List<String> get pushRefspecs => bindings.pushRefspecs(_remotePointer); List<String> get pushRefspecs => bindings.pushRefspecs(_remotePointer);
/// Get the remote repository's reference advertisement list. /// Returns the remote repository's reference list and their associated commit ids.
/// ///
/// [proxy] can be 'auto' to try to auto-detect the proxy from the git configuration or some /// [proxy] can be 'auto' to try to auto-detect the proxy from the git configuration or some
/// specified url. By default connection isn't done through proxy. /// specified url. By default connection isn't done through proxy.
/// ///
/// Returned map keys:
/// - `local` is true if remote head is available locally, false otherwise.
/// - `loid` is the oid of the object the local copy of the remote head is currently
/// pointing to. null if there is no local copy of the remote head.
/// - `name` is the name of the reference.
/// - `oid` is the oid of the object the remote head is currently pointing to.
/// - `symref` is the target of the symbolic reference or empty string.
///
/// Throws a [LibGit2Error] if error occured. /// Throws a [LibGit2Error] if error occured.
List<Map<String, Object?>> ls({ List<Map<String, Object?>> ls({
String? proxy, String? proxy,

View file

@ -120,8 +120,6 @@ class Repository {
/// the first repository is found, or when reaching a directory referenced in [ceilingDirs]. /// the first repository is found, or when reaching a directory referenced in [ceilingDirs].
/// ///
/// The method will automatically detect if the repository is bare (if there is a repository). /// The method will automatically detect if the repository is bare (if there is a repository).
///
/// Throws a [LibGit2Error] if error occured.
static String discover({required String startPath, String? ceilingDirs}) { static String discover({required String startPath, String? ceilingDirs}) {
return bindings.discover( return bindings.discover(
startPath: startPath, startPath: startPath,
@ -164,8 +162,6 @@ class Repository {
/// under refs/namespaces/foo/, use foo as the namespace. /// under refs/namespaces/foo/, use foo as the namespace.
/// ///
/// Pass null to unset. /// Pass null to unset.
///
/// Throws a [LibGit2Error] if error occured.
void setNamespace(String? namespace) { void setNamespace(String? namespace) {
bindings.setNamespace( bindings.setNamespace(
repoPointer: _repoPointer, repoPointer: _repoPointer,
@ -322,8 +318,6 @@ class Repository {
/// will be returned, including global and system configurations (if they are available). /// will be returned, including global and system configurations (if they are available).
/// ///
/// The configuration file must be freed once it's no longer being used by the user. /// The configuration file must be freed once it's no longer being used by the user.
///
/// Throws a [LibGit2Error] if error occured.
Config get config => Config(bindings.config(_repoPointer)); Config get config => Config(bindings.config(_repoPointer));
/// Returns a snapshot of the repository's configuration. /// Returns a snapshot of the repository's configuration.
@ -332,8 +326,6 @@ class Repository {
/// The contents of this snapshot will not change, even if the underlying config files are modified. /// The contents of this snapshot will not change, even if the underlying config files are modified.
/// ///
/// The configuration file must be freed once it's no longer being used by the user. /// The configuration file must be freed once it's no longer being used by the user.
///
/// Throws a [LibGit2Error] if error occured.
Config get configSnapshot => Config(bindings.configSnapshot(_repoPointer)); Config get configSnapshot => Config(bindings.configSnapshot(_repoPointer));
/// Returns [Reference] object pointing to repository head. /// Returns [Reference] object pointing to repository head.
@ -451,8 +443,6 @@ class Repository {
/// ///
/// This looks up the user.name and user.email from the configuration and uses the /// This looks up the user.name and user.email from the configuration and uses the
/// current time as the timestamp, and creates a new signature based on that information. /// current time as the timestamp, and creates a new signature based on that information.
///
/// Throws a [LibGit2Error] if error occured.
Signature get defaultSignature => Signature.defaultSignature(this); Signature get defaultSignature => Signature.defaultSignature(this);
/// Returns the list of commits starting from provided commit [oid]. /// Returns the list of commits starting from provided commit [oid].
@ -648,15 +638,21 @@ class Repository {
List<Branch> get branchesRemote => List<Branch> get branchesRemote =>
Branch.list(repo: this, type: GitBranch.remote); Branch.list(repo: this, type: GitBranch.remote);
/// Lookups a branch by its [name] in a repository. /// Lookups a branch by its [name] and [type] in a repository.
/// ///
/// The branch name will be checked for validity. /// The branch [name] will be checked for validity.
///
/// If branch [type] is [GitBranch.remote] you must include the remote name
/// in the [name] (e.g. "origin/master").
/// ///
/// Should be freed to release allocated memory when no longer needed. /// Should be freed to release allocated memory when no longer needed.
/// ///
/// Throws a [LibGit2Error] if error occured. /// Throws a [LibGit2Error] if error occured.
Branch lookupBranch(String name) { Branch lookupBranch({
return Branch.lookup(repo: this, name: name); required String name,
GitBranch type = GitBranch.local,
}) {
return Branch.lookup(repo: this, name: name, type: type);
} }
/// Creates a new branch pointing at a [target] commit. /// Creates a new branch pointing at a [target] commit.
@ -706,6 +702,8 @@ class Repository {
/// Checks status of the repository and returns map of file paths and their statuses. /// Checks status of the repository and returns map of file paths and their statuses.
/// ///
/// Returns empty map if there are no changes in statuses. /// Returns empty map if there are no changes in statuses.
///
/// Throws a [LibGit2Error] if error occured.
Map<String, Set<GitStatus>> get status { Map<String, Set<GitStatus>> get status {
var result = <String, Set<GitStatus>>{}; var result = <String, Set<GitStatus>>{};
var list = status_bindings.listNew(_repoPointer); var list = status_bindings.listNew(_repoPointer);
@ -789,14 +787,14 @@ class Repository {
String ourRef = 'HEAD', String ourRef = 'HEAD',
}) { }) {
final ref = lookupReference(ourRef); final ref = lookupReference(ourRef);
final head = commit_bindings.annotatedLookup( final head = AnnotatedCommit.lookup(
repoPointer: _repoPointer, repo: this,
oidPointer: theirHead.pointer, oid: theirHead,
); );
final analysisInt = merge_bindings.analysis( final analysisInt = merge_bindings.analysis(
repoPointer: _repoPointer, repoPointer: _repoPointer,
ourRefPointer: ref.pointer, ourRefPointer: ref.pointer,
theirHeadPointer: head, theirHeadPointer: head.pointer,
theirHeadsLen: 1, theirHeadsLen: 1,
); );
@ -807,7 +805,7 @@ class Repository {
(e) => analysisInt[1] == e.value, (e) => analysisInt[1] == e.value,
); );
commit_bindings.annotatedFree(head.value); head.free();
ref.free(); ref.free();
return [analysisSet, mergePreference]; return [analysisSet, mergePreference];
@ -820,18 +818,18 @@ class Repository {
/// ///
/// Throws a [LibGit2Error] if error occured. /// Throws a [LibGit2Error] if error occured.
void merge(Oid oid) { void merge(Oid oid) {
final theirHead = commit_bindings.annotatedLookup( final theirHead = AnnotatedCommit.lookup(
repoPointer: _repoPointer, repo: this,
oidPointer: oid.pointer, oid: oid,
); );
merge_bindings.merge( merge_bindings.merge(
repoPointer: _repoPointer, repoPointer: _repoPointer,
theirHeadsPointer: theirHead, theirHeadsPointer: theirHead.pointer,
theirHeadsLen: 1, theirHeadsLen: 1,
); );
commit_bindings.annotatedFree(theirHead.value); theirHead.free();
} }
/// Merges two files as they exist in the index, using the given common ancestor /// Merges two files as they exist in the index, using the given common ancestor
@ -1092,23 +1090,30 @@ class Repository {
return a.diff(newBlob: b, oldAsPath: aPath, newAsPath: bPath); return a.diff(newBlob: b, oldAsPath: aPath, newAsPath: bPath);
} }
/// Applies the [diff] to the given repository, making changes directly in the working directory. /// Applies the [diff] to the given repository, making changes directly in the
/// working directory (default), the index, or both.
/// ///
/// Throws a [LibGit2Error] if error occured. /// Throws a [LibGit2Error] if error occured.
void apply(Diff diff) { void apply({
required Diff diff,
GitApplyLocation location = GitApplyLocation.workdir,
}) {
diff_bindings.apply( diff_bindings.apply(
repoPointer: _repoPointer, repoPointer: _repoPointer,
diffPointer: diff.pointer, diffPointer: diff.pointer,
location: GitApplyLocation.workdir.value, location: location.value,
); );
} }
/// Checks if the [diff] will apply to HEAD. /// Checks if the [diff] will apply to the working directory (default), the index, or both.
bool applies(Diff diff) { bool applies({
required Diff diff,
GitApplyLocation location = GitApplyLocation.workdir,
}) {
return diff_bindings.apply( return diff_bindings.apply(
repoPointer: _repoPointer, repoPointer: _repoPointer,
diffPointer: diff.pointer, diffPointer: diff.pointer,
location: GitApplyLocation.index.value, location: location.value,
check: true, check: true,
); );
} }
@ -1162,7 +1167,7 @@ class Repository {
/// Removes a single stashed state from the stash list. /// Removes a single stashed state from the stash list.
/// ///
/// Throws a [LibGit2Error] if error occured. /// Throws a [LibGit2Error] if error occured.
void dropStash([int index = 0]) { void dropStash({int index = 0}) {
Stash.drop(repo: this, index: index); Stash.drop(repo: this, index: index);
} }
@ -1191,8 +1196,6 @@ class Repository {
} }
/// Returns a list of the configured remotes for a repository. /// Returns a list of the configured remotes for a repository.
///
/// Throws a [LibGit2Error] if error occured.
List<String> get remotes => Remote.list(this); List<String> get remotes => Remote.list(this);
/// Lookups remote with provided [name]. /// Lookups remote with provided [name].
@ -1246,8 +1249,6 @@ class Repository {
/// ///
/// Returned value can be either `true`, `false`, `null` (if the attribute was not set at all), /// Returned value can be either `true`, `false`, `null` (if the attribute was not set at all),
/// or a [String] value, if the attribute was set to an actual string. /// or a [String] value, if the attribute was set to an actual string.
///
/// Throws a [LibGit2Error] if error occured.
Object? getAttribute({ Object? getAttribute({
required String path, required String path,
required String name, required String name,
@ -1511,8 +1512,6 @@ class Repository {
} }
/// Returns a list with all tracked submodules paths of a repository. /// Returns a list with all tracked submodules paths of a repository.
///
/// Throws a [LibGit2Error] if error occured.
List<String> get submodules => Submodule.list(this); List<String> get submodules => Submodule.list(this);
/// Lookups submodule by name or path. /// Lookups submodule by name or path.

View file

@ -28,8 +28,6 @@ class RevWalk {
/// Changes the sorting mode when iterating through the repository's contents. /// Changes the sorting mode when iterating through the repository's contents.
/// ///
/// Changing the sorting mode resets the walker. /// Changing the sorting mode resets the walker.
///
/// Throws a [LibGit2Error] if error occured.
void sorting(Set<GitSort> sorting) { void sorting(Set<GitSort> sorting) {
bindings.sorting( bindings.sorting(
walkerPointer: _revWalkPointer, walkerPointer: _revWalkPointer,
@ -79,8 +77,6 @@ class RevWalk {
/// Simplify the history by first-parent. /// Simplify the history by first-parent.
/// ///
/// No parents other than the first for each commit will be enqueued. /// No parents other than the first for each commit will be enqueued.
///
/// Throws a [LibGit2Error] if error occured.
void simplifyFirstParent() => bindings.simplifyFirstParent(_revWalkPointer); void simplifyFirstParent() => bindings.simplifyFirstParent(_revWalkPointer);
/// Releases memory allocated for [RevWalk] object. /// Releases memory allocated for [RevWalk] object.

View file

@ -9,7 +9,7 @@ class Signature {
/// Initializes a new instance of [Signature] class from provided pointer to /// Initializes a new instance of [Signature] class from provided pointer to
/// signature object in memory. /// signature object in memory.
/// ///
/// Should be freed with `free()` to release allocated memory. /// Should be freed to release allocated memory.
Signature(this._signaturePointer); Signature(this._signaturePointer);
/// Initializes a new instance of [Signature] class from provided [name], [email], /// Initializes a new instance of [Signature] class from provided [name], [email],
@ -17,7 +17,7 @@ class Signature {
/// ///
/// If [time] isn't provided [Signature] will be created with a timestamp of 'now'. /// If [time] isn't provided [Signature] will be created with a timestamp of 'now'.
/// ///
/// Should be freed with `free()` to release allocated memory. /// Should be freed to release allocated memory.
Signature.create({ Signature.create({
required String name, required String name,
required String email, required String email,
@ -47,8 +47,6 @@ class Signature {
/// ///
/// This looks up the user.name and user.email from the configuration and uses the /// This looks up the user.name and user.email from the configuration and uses the
/// current time as the timestamp, and creates a new signature based on that information. /// current time as the timestamp, and creates a new signature based on that information.
///
/// Throws a [LibGit2Error] if error occured.
static Signature defaultSignature(Repository repo) => static Signature defaultSignature(Repository repo) =>
Signature(bindings.defaultSignature(repo.pointer)); Signature(bindings.defaultSignature(repo.pointer));

View file

@ -108,16 +108,13 @@ class Submodule {
} }
/// Returns a list with all tracked submodules paths of a repository. /// Returns a list with all tracked submodules paths of a repository.
///
/// Throws a [LibGit2Error] if error occured.
static List<String> list(Repository repo) => bindings.list(repo.pointer); static List<String> list(Repository repo) => bindings.list(repo.pointer);
/// Opens the repository for a submodule. /// Opens the repository for a submodule.
/// ///
/// This is a newly opened repository object. The caller is responsible for calling /// This is a newly opened repository object. The caller is responsible for freeing it
/// `free()` on it when done. Multiple calls to this function will return distinct /// when done. Multiple calls to this function will return distinct git repository objects.
/// git repository objects. This will only work if the submodule is checked out into /// This will only work if the submodule is checked out into the working directory.
/// the working directory.
/// ///
/// Throws a [LibGit2Error] if error occured. /// Throws a [LibGit2Error] if error occured.
Repository open() { Repository open() {
@ -129,8 +126,6 @@ class Submodule {
/// This looks at a submodule and tries to determine the status. How deeply it examines /// This looks at a submodule and tries to determine the status. How deeply it examines
/// the working directory to do this will depend on the combination of [GitSubmoduleIgnore] /// the working directory to do this will depend on the combination of [GitSubmoduleIgnore]
/// values provided to [ignore] . /// values provided to [ignore] .
///
/// Throws a [LibGit2Error] if error occured.
Set<GitSubmoduleStatus> status({ Set<GitSubmoduleStatus> status({
GitSubmoduleIgnore ignore = GitSubmoduleIgnore.unspecified, GitSubmoduleIgnore ignore = GitSubmoduleIgnore.unspecified,
}) { }) {
@ -151,8 +146,6 @@ class Submodule {
/// config, acting like `git submodule sync`. This is useful if you have altered the URL /// config, acting like `git submodule sync`. This is useful if you have altered the URL
/// for the submodule (or it has been altered by a fetch of upstream changes) and you /// for the submodule (or it has been altered by a fetch of upstream changes) and you
/// need to update your local repo. /// need to update your local repo.
///
/// Throws a [LibGit2Error] if error occured.
void sync() => bindings.sync(_submodulePointer); void sync() => bindings.sync(_submodulePointer);
/// Rereads submodule info from config, index, and HEAD. /// Rereads submodule info from config, index, and HEAD.
@ -181,8 +174,6 @@ class Submodule {
/// ///
/// After calling this, you may wish to call [sync] to write the changes to /// After calling this, you may wish to call [sync] to write the changes to
/// the checked out submodule repository. /// the checked out submodule repository.
///
/// Throws a [LibGit2Error] if error occured.
set url(String url) { set url(String url) {
bindings.setUrl( bindings.setUrl(
repoPointer: bindings.owner(_submodulePointer), repoPointer: bindings.owner(_submodulePointer),
@ -198,8 +189,6 @@ class Submodule {
/// ///
/// After calling this, you may wish to call [sync] to write the changes to /// After calling this, you may wish to call [sync] to write the changes to
/// the checked out submodule repository. /// the checked out submodule repository.
///
/// Throws a [LibGit2Error] if error occured.
set branch(String branch) { set branch(String branch) {
bindings.setBranch( bindings.setBranch(
repoPointer: bindings.owner(_submodulePointer), repoPointer: bindings.owner(_submodulePointer),
@ -243,8 +232,6 @@ class Submodule {
/// Sets the ignore rule for the submodule in the configuration. /// Sets the ignore rule for the submodule in the configuration.
/// ///
/// This does not affect any currently-loaded instances. /// This does not affect any currently-loaded instances.
///
/// Throws a [LibGit2Error] if error occured.
set ignore(GitSubmoduleIgnore ignore) { set ignore(GitSubmoduleIgnore ignore) {
final repo = bindings.owner(_submodulePointer); final repo = bindings.owner(_submodulePointer);
bindings.setIgnore(repoPointer: repo, name: name, ignore: ignore.value); bindings.setIgnore(repoPointer: repo, name: name, ignore: ignore.value);
@ -261,8 +248,6 @@ class Submodule {
/// Sets the update rule for the submodule in the configuration. /// Sets the update rule for the submodule in the configuration.
/// ///
/// This setting won't affect any existing instances. /// This setting won't affect any existing instances.
///
/// Throws a [LibGit2Error] if error occured.
set updateRule(GitSubmoduleUpdate rule) { set updateRule(GitSubmoduleUpdate rule) {
bindings.setUpdateRule( bindings.setUpdateRule(
repoPointer: bindings.owner(_submodulePointer), repoPointer: bindings.owner(_submodulePointer),

View file

@ -93,8 +93,6 @@ class Tree {
} }
/// Creates a diff between a tree and repository index. /// Creates a diff between a tree and repository index.
///
/// Throws a [LibGit2Error] if error occured.
Diff diffToIndex({ Diff diffToIndex({
required Index index, required Index index,
Set<GitDiff> flags = const {GitDiff.normal}, Set<GitDiff> flags = const {GitDiff.normal},

View file

@ -24,13 +24,9 @@ class TreeBuilder {
int get length => bindings.entryCount(_treeBuilderPointer); int get length => bindings.entryCount(_treeBuilderPointer);
/// Writes the contents of the tree builder as a tree object. /// Writes the contents of the tree builder as a tree object.
///
/// Throws a [LibGit2Error] if error occured.
Oid write() => Oid(bindings.write(_treeBuilderPointer)); Oid write() => Oid(bindings.write(_treeBuilderPointer));
/// Clears all the entires in the tree builder. /// Clears all the entires in the tree builder.
///
/// Throws a [LibGit2Error] if error occured.
void clear() => bindings.clear(_treeBuilderPointer); void clear() => bindings.clear(_treeBuilderPointer);
/// Returns an entry from the tree builder from its filename. /// Returns an entry from the tree builder from its filename.

View file

@ -1,3 +1,5 @@
// coverage:ignore-file
import 'dart:io'; import 'dart:io';
import 'dart:ffi'; import 'dart:ffi';
import 'bindings/libgit2_bindings.dart'; import 'bindings/libgit2_bindings.dart';

View file

@ -11,7 +11,7 @@ class Worktree {
/// If [ref] is provided, no new branch will be created but specified [ref] will /// If [ref] is provided, no new branch will be created but specified [ref] will
/// be used instead. /// be used instead.
/// ///
/// Should be freed with `free()` to release allocated memory. /// Should be freed to release allocated memory.
/// ///
/// Throws a [LibGit2Error] if error occured. /// Throws a [LibGit2Error] if error occured.
Worktree.create({ Worktree.create({
@ -31,7 +31,7 @@ class Worktree {
/// Initializes a new instance of [Worktree] class by looking up existing worktree /// Initializes a new instance of [Worktree] class by looking up existing worktree
/// with provided [Repository] object and worktree [name]. /// with provided [Repository] object and worktree [name].
/// ///
/// Should be freed with `free()` to release allocated memory. /// Should be freed to release allocated memory.
/// ///
/// Throws a [LibGit2Error] if error occured. /// Throws a [LibGit2Error] if error occured.
Worktree.lookup({required Repository repo, required String name}) { Worktree.lookup({required Repository repo, required String name}) {
@ -56,8 +56,6 @@ class Worktree {
/// ///
/// A worktree may be locked if the linked working tree is stored on a portable /// A worktree may be locked if the linked working tree is stored on a portable
/// device which is not available. /// device which is not available.
///
/// Throws a [LibGit2Error] if error occured.
bool get isLocked => bindings.isLocked(_worktreePointer); bool get isLocked => bindings.isLocked(_worktreePointer);
/// Locks worktree if not already locked. /// Locks worktree if not already locked.
@ -78,8 +76,6 @@ class Worktree {
/// Prunes working tree. /// Prunes working tree.
/// ///
/// Prune the working tree, that is remove the git data structures on disk. /// Prune the working tree, that is remove the git data structures on disk.
///
/// Throws a [LibGit2Error] if error occured.
void prune() => bindings.prune(_worktreePointer); void prune() => bindings.prune(_worktreePointer);
/// Checks if worktree is valid. /// Checks if worktree is valid.

View file

@ -57,7 +57,10 @@ void main() {
group('Blame', () { group('Blame', () {
test('successfully gets the blame for provided file', () { test('successfully gets the blame for provided file', () {
final blame = repo.blame(path: 'feature_file'); final blame = repo.blame(
path: 'feature_file',
oldestCommit: repo['f17d0d4'],
);
expect(blame.length, 2); expect(blame.length, 2);
@ -79,6 +82,33 @@ void main() {
blame.free(); blame.free();
}); });
test('throws when provided file path is invalid', () {
expect(
() => repo.blame(path: 'invalid'),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"the path 'invalid' does not exist in the given tree",
),
),
);
});
test(
'successfully gets the blame for provided file with minMatchCharacters set',
() {
final blame = repo.blame(
path: 'feature_file',
minMatchCharacters: 1,
flags: {GitBlameFlag.trackCopiesSameFile},
);
expect(blame.length, 2);
blame.free();
});
test('successfully gets the blame for provided line', () { test('successfully gets the blame for provided line', () {
final blame = repo.blame(path: 'feature_file'); final blame = repo.blame(path: 'feature_file');
@ -102,14 +132,32 @@ void main() {
test('throws when provided index for hunk is invalid', () { test('throws when provided index for hunk is invalid', () {
final blame = repo.blame(path: 'feature_file'); final blame = repo.blame(path: 'feature_file');
expect(() => blame[10], throwsA(isA<RangeError>())); expect(
() => blame[10],
throwsA(
isA<RangeError>().having(
(e) => e.message,
'error',
'10 is out of bounds',
),
),
);
blame.free(); blame.free();
}); });
test('throws when provided line number for hunk is invalid', () { test('throws when provided line number for hunk is invalid', () {
final blame = repo.blame(path: 'feature_file'); final blame = repo.blame(path: 'feature_file');
expect(() => blame.forLine(10), throwsA(isA<RangeError>())); expect(
() => blame.forLine(10),
throwsA(
isA<RangeError>().having(
(e) => e.message,
'error',
'10 is out of bounds',
),
),
);
blame.free(); blame.free();
}); });
@ -119,7 +167,7 @@ void main() {
() { () {
final blame = repo.blame( final blame = repo.blame(
path: 'feature_file', path: 'feature_file',
newestCommit: repo['fc38877b2552ab554752d9a77e1f48f738cca79b'], newestCommit: repo['fc38877'],
flags: {GitBlameFlag.ignoreWhitespace}, flags: {GitBlameFlag.ignoreWhitespace},
); );
@ -143,6 +191,35 @@ void main() {
blame.free(); blame.free();
}); });
test(
'successfully gets the blame for provided file with minLine and maxLine set',
() {
final blame = repo.blame(
path: 'feature_file',
minLine: 1,
maxLine: 1,
);
expect(blame.length, 1);
for (var i = 0; i < blame.length; i++) {
expect(blame[i].linesCount, 1);
expect(blame[i].finalCommitOid.sha, hunks[i]['finalCommitOid']);
expect(blame[i].finalStartLineNumber, hunks[i]['finalStartLineNumber']);
expect(blame[i].finalCommitter, hunks[i]['finalCommitter']);
expect(blame[i].originCommitOid.sha, hunks[i]['originCommitOid']);
expect(
blame[i].originStartLineNumber,
hunks[i]['originStartLineNumber'],
);
expect(blame[i].originCommitter, hunks[i]['originCommitter']);
expect(blame[i].isBoundary, hunks[i]['isBoundary']);
expect(blame[i].originPath, 'feature_file');
}
blame.free();
});
test('returns string representation of BlameHunk object', () { test('returns string representation of BlameHunk object', () {
final blame = repo.blame(path: 'feature_file'); final blame = repo.blame(path: 'feature_file');
expect(blame.toString(), contains('BlameHunk{')); expect(blame.toString(), contains('BlameHunk{'));

View file

@ -1,3 +1,4 @@
import 'dart:ffi';
import 'dart:io'; import 'dart:io';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:libgit2dart/libgit2dart.dart'; import 'package:libgit2dart/libgit2dart.dart';
@ -28,6 +29,19 @@ void main() {
expect(blob, isA<Blob>()); expect(blob, isA<Blob>());
}); });
test('throws when trying to lookup with invalid oid', () {
expect(
() => repo.lookupBlob(repo['0' * 40]),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
'odb: cannot read object: null OID cannot exist',
),
),
);
});
test('returns correct values', () { test('returns correct values', () {
expect(blob.oid.sha, blobSHA); expect(blob.oid.sha, blobSHA);
expect(blob.isBinary, false); expect(blob.isBinary, false);
@ -47,6 +61,20 @@ void main() {
newBlob.free(); newBlob.free();
}); });
test('throws when trying to create new blob and error occurs', () {
final nullRepo = Repository(nullptr);
expect(
() => Blob.create(repo: nullRepo, content: ''),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'repo'",
),
),
);
});
test('successfully creates new blob from file at provided relative path', test('successfully creates new blob from file at provided relative path',
() { () {
final oid = repo.createBlobFromWorkdir('feature_file'); final oid = repo.createBlobFromWorkdir('feature_file');
@ -66,24 +94,13 @@ void main() {
throwsA( throwsA(
isA<LibGit2Error>().having( isA<LibGit2Error>().having(
(e) => e.toString(), (e) => e.toString(),
'message', 'error',
"could not find '${repo.workdir}invalid/path.txt' to stat: No such file or directory", "could not find '${repo.workdir}invalid/path.txt' to stat: No such file or directory",
), ),
), ),
); );
}); });
test(
'throws when creating new blob from path that is outside of working directory',
() {
final outsideFile =
File('${Directory.current.absolute.path}/test/blob_test.dart');
expect(
() => repo.createBlobFromWorkdir(outsideFile.path),
throwsA(isA<LibGit2Error>()),
);
});
test('successfully creates new blob from file at provided path', () { test('successfully creates new blob from file at provided path', () {
final outsideFile = final outsideFile =
File('${Directory.current.absolute.path}/test/blob_test.dart'); File('${Directory.current.absolute.path}/test/blob_test.dart');
@ -96,6 +113,19 @@ void main() {
newBlob.free(); newBlob.free();
}); });
test('throws when trying to create from invalid path', () {
expect(
() => repo.createBlobFromDisk('invalid.file'),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"failed to resolve path 'invalid.file': No such file or directory",
),
),
);
});
group('diff', () { group('diff', () {
const path = 'feature_file'; const path = 'feature_file';
const blobPatch = """ const blobPatch = """

View file

@ -1,3 +1,4 @@
import 'dart:ffi';
import 'dart:io'; import 'dart:io';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:libgit2dart/libgit2dart.dart'; import 'package:libgit2dart/libgit2dart.dart';
@ -46,19 +47,53 @@ void main() {
expect(repo.branchesRemote, []); expect(repo.branchesRemote, []);
}); });
test('throws when trying to return list and error occurs', () {
final nullRepo = Repository(nullptr);
expect(
() => Branch.list(repo: nullRepo),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'repo'",
),
),
);
});
test('returns a branch with provided name', () { test('returns a branch with provided name', () {
final branch = repo.lookupBranch('master'); final branch = repo.lookupBranch(name: 'master');
expect(branch.target.sha, lastCommit.sha); expect(branch.target.sha, lastCommit.sha);
branch.free(); branch.free();
}); });
test('throws when provided name not found', () { test('throws when provided name not found', () {
expect(() => repo.lookupBranch('invalid'), throwsA(isA<LibGit2Error>())); expect(
() => repo.lookupBranch(name: 'invalid'),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"cannot locate local branch 'invalid'",
),
),
);
expect(
() => repo.lookupBranch(name: 'origin/invalid', type: GitBranch.remote),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"cannot locate remote-tracking branch 'origin/invalid'",
),
),
);
}); });
test('checks if branch is current head', () { test('checks if branch is current head', () {
final masterBranch = repo.lookupBranch('master'); final masterBranch = repo.lookupBranch(name: 'master');
final featureBranch = repo.lookupBranch('feature'); final featureBranch = repo.lookupBranch(name: 'feature');
expect(masterBranch.isHead, true); expect(masterBranch.isHead, true);
expect(featureBranch.isHead, false); expect(featureBranch.isHead, false);
@ -67,12 +102,65 @@ void main() {
featureBranch.free(); featureBranch.free();
}); });
test('throws when checking if branch is current head and error occurs', () {
final nullBranch = Branch(nullptr);
expect(
() => nullBranch.isHead,
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'branch'",
),
),
);
});
test('checks if branch is checked out', () {
final masterBranch = repo.lookupBranch(name: 'master');
final featureBranch = repo.lookupBranch(name: 'feature');
expect(masterBranch.isCheckedOut, true);
expect(featureBranch.isCheckedOut, false);
masterBranch.free();
featureBranch.free();
});
test('throws when checking if branch is checked out and error occurs', () {
final nullBranch = Branch(nullptr);
expect(
() => nullBranch.isCheckedOut,
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'branch'",
),
),
);
});
test('returns name', () { test('returns name', () {
final branch = repo.lookupBranch('master'); final branch = repo.lookupBranch(name: 'master');
expect(branch.name, 'master'); expect(branch.name, 'master');
branch.free(); branch.free();
}); });
test('throws when getting name and error occurs', () {
final nullBranch = Branch(nullptr);
expect(
() => nullBranch.name,
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'ref'",
),
),
);
});
group('create()', () { group('create()', () {
test('successfully creates', () { test('successfully creates', () {
final commit = repo.lookupCommit(lastCommit); final commit = repo.lookupCommit(lastCommit);
@ -95,7 +183,14 @@ void main() {
expect( expect(
() => repo.createBranch(name: 'feature', target: commit), () => repo.createBranch(name: 'feature', target: commit),
throwsA(isA<LibGit2Error>()), throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"failed to write reference 'refs/heads/feature': "
"a reference with that name already exists.",
),
),
); );
commit.free(); commit.free();
@ -127,15 +222,27 @@ void main() {
repo.deleteBranch('feature'); repo.deleteBranch('feature');
expect( expect(
() => repo.lookupBranch('feature'), () => repo.lookupBranch(name: 'feature'),
throwsA(isA<LibGit2Error>()), throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"cannot locate local branch 'feature'",
),
),
); );
}); });
test('throws when trying to delete current HEAD', () { test('throws when trying to delete current HEAD', () {
expect( expect(
() => repo.deleteBranch('master'), () => repo.deleteBranch('master'),
throwsA(isA<LibGit2Error>()), throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"cannot delete branch 'refs/heads/master' as it is the current HEAD of the repository.",
),
),
); );
}); });
}); });
@ -143,13 +250,19 @@ void main() {
group('rename()', () { group('rename()', () {
test('successfully renames', () { test('successfully renames', () {
repo.renameBranch(oldName: 'feature', newName: 'renamed'); repo.renameBranch(oldName: 'feature', newName: 'renamed');
final branch = repo.lookupBranch('renamed'); final branch = repo.lookupBranch(name: 'renamed');
final branches = repo.branches; final branches = repo.branches;
expect(branches.length, 2); expect(branches.length, 2);
expect( expect(
() => repo.lookupBranch('feature'), () => repo.lookupBranch(name: 'feature'),
throwsA(isA<LibGit2Error>()), throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"cannot locate local branch 'feature'",
),
),
); );
expect(branch.target, featureCommit); expect(branch.target, featureCommit);
@ -162,7 +275,14 @@ void main() {
test('throws when name already exists', () { test('throws when name already exists', () {
expect( expect(
() => repo.renameBranch(oldName: 'feature', newName: 'master'), () => repo.renameBranch(oldName: 'feature', newName: 'master'),
throwsA(isA<LibGit2Error>()), throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"failed to write reference 'refs/heads/master': "
"a reference with that name already exists.",
),
),
); );
}); });
@ -172,7 +292,7 @@ void main() {
newName: 'feature', newName: 'feature',
force: true, force: true,
); );
final branch = repo.lookupBranch('feature'); final branch = repo.lookupBranch(name: 'feature');
expect(branch.target, lastCommit); expect(branch.target, lastCommit);
@ -182,13 +302,19 @@ void main() {
test('throws when name is invalid', () { test('throws when name is invalid', () {
expect( expect(
() => repo.renameBranch(oldName: 'feature', newName: 'inv@{id'), () => repo.renameBranch(oldName: 'feature', newName: 'inv@{id'),
throwsA(isA<LibGit2Error>()), throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"the given reference name 'refs/heads/inv@{id' is not valid",
),
),
); );
}); });
}); });
test('returns string representation of Branch object', () { test('returns string representation of Branch object', () {
final branch = repo.lookupBranch('master'); final branch = repo.lookupBranch(name: 'master');
expect(branch.toString(), contains('Branch{')); expect(branch.toString(), contains('Branch{'));
branch.free(); branch.free();
}); });

View file

@ -23,21 +23,61 @@ void main() {
File('${tmpDir.path}/feature_file').writeAsStringSync('edit'); File('${tmpDir.path}/feature_file').writeAsStringSync('edit');
expect(repo.status, contains('feature_file')); expect(repo.status, contains('feature_file'));
repo.checkout(refName: 'HEAD', strategy: {GitCheckout.force}); repo.checkout(
refName: 'HEAD',
strategy: {GitCheckout.force},
paths: ['feature_file'],
);
expect(repo.status, isEmpty); expect(repo.status, isEmpty);
}); });
test(
'throws when trying to checkout head with invalid alternative directory',
() {
expect(
() => repo.checkout(
refName: 'HEAD',
directory: 'not/there',
),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"failed to make directory 'not/there': No such file or directory",
),
),
);
});
test('successfully checkouts index', () { test('successfully checkouts index', () {
File('${repo.workdir}feature_file').writeAsStringSync('edit'); File('${repo.workdir}feature_file').writeAsStringSync('edit');
expect(repo.status, contains('feature_file')); expect(repo.status, contains('feature_file'));
repo.checkout(strategy: { repo.checkout(
strategy: {
GitCheckout.force, GitCheckout.force,
GitCheckout.conflictStyleMerge, GitCheckout.conflictStyleMerge,
}); },
paths: ['feature_file'],
);
expect(repo.status, isEmpty); expect(repo.status, isEmpty);
}); });
test(
'throws when trying to checkout index with invalid alternative directory',
() {
expect(
() => repo.checkout(directory: 'not/there'),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"failed to make directory 'not/there': No such file or directory",
),
),
);
});
test('successfully checkouts tree', () { test('successfully checkouts tree', () {
final masterHead = repo.lookupCommit( final masterHead = repo.lookupCommit(
repo['821ed6e80627b8769d170a293862f9fc60825226'], repo['821ed6e80627b8769d170a293862f9fc60825226'],
@ -68,6 +108,24 @@ void main() {
masterHead.free(); masterHead.free();
}); });
test(
'throws when trying to checkout tree with invalid alternative directory',
() {
expect(
() => repo.checkout(
refName: 'refs/heads/feature',
directory: 'not/there',
),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"failed to make directory 'not/there': No such file or directory",
),
),
);
});
test('successfully checkouts with alrenative directory', () { test('successfully checkouts with alrenative directory', () {
final altDir = Directory('${Directory.systemTemp.path}/alt_dir'); final altDir = Directory('${Directory.systemTemp.path}/alt_dir');
// making sure there is no directory // making sure there is no directory

View file

@ -1,3 +1,4 @@
import 'dart:ffi';
import 'dart:io'; import 'dart:io';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:libgit2dart/libgit2dart.dart'; import 'package:libgit2dart/libgit2dart.dart';
@ -41,12 +42,44 @@ void main() {
}); });
group('Commit', () { group('Commit', () {
test('successfully returns when 40 char sha hex is provided', () { test('successfully lookups for provided oid', () {
final commit = repo.lookupCommit(mergeCommit); final commit = repo.lookupCommit(mergeCommit);
expect(commit, isA<Commit>()); expect(commit, isA<Commit>());
commit.free(); commit.free();
}); });
test('throws when trying to lookup with invalid oid', () {
expect(
() => repo.lookupCommit(repo['0' * 40]),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"odb: cannot read object: null OID cannot exist",
),
),
);
});
test('successfully lookups annotated commit for provided oid', () {
final annotated = AnnotatedCommit.lookup(repo: repo, oid: mergeCommit);
expect(annotated, isA<AnnotatedCommit>());
annotated.free();
});
test('throws when trying to lookup annotated commit with invalid oid', () {
expect(
() => AnnotatedCommit.lookup(repo: repo, oid: repo['0' * 40]),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"odb: cannot read object: null OID cannot exist",
),
),
);
});
test('successfully reverts commit', () { test('successfully reverts commit', () {
final to = repo.lookupCommit( final to = repo.lookupCommit(
repo['78b8bf123e3952c970ae5c1ce0a3ea1d1336f6e8'], repo['78b8bf123e3952c970ae5c1ce0a3ea1d1336f6e8'],
@ -66,6 +99,23 @@ void main() {
from.free(); from.free();
}); });
test('throws when trying to revert commit and error occurs', () {
final nullCommit = Commit(nullptr);
expect(
() => repo.revertCommit(
revertCommit: nullCommit,
ourCommit: nullCommit,
),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'revert_commit'",
),
),
);
});
test('successfully creates commit', () { test('successfully creates commit', () {
final parent = repo.lookupCommit(mergeCommit); final parent = repo.lookupCommit(mergeCommit);
final oid = repo.createCommit( final oid = repo.createCommit(
@ -148,6 +198,30 @@ void main() {
commit.free(); commit.free();
}); });
test('throws when trying to create commit and error occurs', () {
final parent = repo.lookupCommit(mergeCommit);
final nullRepo = Repository(nullptr);
expect(
() => nullRepo.createCommit(
message: message,
author: author,
commiter: commiter,
tree: tree,
parents: [parent],
),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'git_tree_owner(tree) == repo'",
),
),
);
parent.free();
});
test('returns string representation of Commit object', () { test('returns string representation of Commit object', () {
final commit = repo.lookupCommit(mergeCommit); final commit = repo.lookupCommit(mergeCommit);
expect(commit.toString(), contains('Commit{')); expect(commit.toString(), contains('Commit{'));

View file

@ -82,6 +82,20 @@ void main() {
expect(credentials.toString(), contains('KeypairFromAgent{')); expect(credentials.toString(), contains('KeypairFromAgent{'));
}); });
test('sucessfully clones repository with provided username', () {
final callbacks = const Callbacks(credentials: Username('git'));
final repo = Repository.clone(
url: 'https://git@github.com/libgit2/TestGitRepository',
localPath: cloneDir.path,
callbacks: callbacks,
);
expect(repo.isEmpty, false);
repo.free();
});
test('sucessfully clones repository with provided keypair', () { test('sucessfully clones repository with provided keypair', () {
final keypair = const Keypair( final keypair = const Keypair(
username: 'git', username: 'git',

View file

@ -1,3 +1,4 @@
import 'dart:ffi';
import 'dart:io'; import 'dart:io';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:libgit2dart/libgit2dart.dart'; import 'package:libgit2dart/libgit2dart.dart';
@ -22,6 +23,20 @@ void main() {
expect(repo.describe(), 'v0.2'); expect(repo.describe(), 'v0.2');
}); });
test('throws when trying to describe and error occurs', () {
final nullRepo = Repository(nullptr);
expect(
() => nullRepo.describe(),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'repo'",
),
),
);
});
test('successfully describes commit', () { test('successfully describes commit', () {
repo.deleteTag('v0.2'); repo.deleteTag('v0.2');
@ -33,7 +48,16 @@ void main() {
test('throws when trying to describe and no reference found', () { test('throws when trying to describe and no reference found', () {
final commit = repo.lookupCommit(repo['f17d0d48']); final commit = repo.lookupCommit(repo['f17d0d48']);
expect(() => repo.describe(commit: commit), throwsA(isA<LibGit2Error>())); expect(
() => repo.describe(commit: commit),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"cannot describe - no tags can describe 'f17d0d48eae3aa08cecf29128a35e310c97b3521'.",
),
),
);
commit.free(); commit.free();
}); });

View file

@ -1,3 +1,4 @@
import 'dart:ffi';
import 'dart:io'; import 'dart:io';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:libgit2dart/libgit2dart.dart'; import 'package:libgit2dart/libgit2dart.dart';
@ -141,6 +142,22 @@ index e69de29..c217c63 100644
diff.free(); diff.free();
}); });
test('throws when trying to diff between tree and workdir and error occurs',
() {
final nullRepo = Repository(nullptr);
final nullTree = Tree(nullptr);
expect(
() => nullRepo.diff(a: nullTree),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'repo'",
),
),
);
});
test('successfully returns diff between tree and index', () { test('successfully returns diff between tree and index', () {
final index = repo.index; final index = repo.index;
final head = repo.head; final head = repo.head;
@ -179,9 +196,34 @@ index e69de29..c217c63 100644
diff.free(); diff.free();
}); });
test('throws when trying to diff between tree and tree and error occurs',
() {
final nullRepo = Repository(nullptr);
final nullTree = Tree(nullptr);
expect(
() => nullRepo.diff(a: nullTree, b: nullTree),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'repo'",
),
),
);
});
test('throws when trying to diff between null and tree', () { test('throws when trying to diff between null and tree', () {
final tree = repo.lookupTree(repo['b85d53c']); final tree = repo.lookupTree(repo['b85d53c']);
expect(() => repo.diff(a: null, b: tree), throwsA(isA<ArgumentError>())); expect(
() => repo.diff(a: null, b: tree),
throwsA(
isA<ArgumentError>().having(
(e) => e.message,
'error',
"Must not be null",
),
),
);
tree.free(); tree.free();
}); });
@ -216,31 +258,51 @@ index e69de29..c217c63 100644
expect(diff.length, 1); expect(diff.length, 1);
expect(stats.filesChanged, 1); expect(stats.filesChanged, 1);
expect(stats.insertions, 1); expect(stats.insertions, 1);
expect(diff.patchId.sha, '699556913185bc38632ae20a49d5c18b9233335e'); expect(diff.patchOid.sha, '699556913185bc38632ae20a49d5c18b9233335e');
stats.free(); stats.free();
diff.free(); diff.free();
}); });
test( test('checks if diff can be applied to repository', () {
'checks if diff can be applied to repository and successfully applies it', final diff1 = repo.diff();
() { expect(repo.applies(diff: diff1, location: GitApplyLocation.both), false);
final diff2 = Diff.parse(patchText);
repo.checkout(refName: 'HEAD', strategy: {GitCheckout.force});
expect(repo.applies(diff: diff2, location: GitApplyLocation.both), true);
diff1.free();
diff2.free();
});
test('successfully applies diff to repository', () {
final diff = Diff.parse(patchText); final diff = Diff.parse(patchText);
final file = File('${tmpDir.path}/subdir/modified_file'); final file = File('${tmpDir.path}/subdir/modified_file');
repo.reset( repo.checkout(refName: 'HEAD', strategy: {GitCheckout.force});
oid: repo['a763aa560953e7cfb87ccbc2f536d665aa4dff22'],
resetType: GitReset.hard,
);
expect(file.readAsStringSync(), ''); expect(file.readAsStringSync(), '');
expect(repo.applies(diff), true); repo.apply(diff: diff);
repo.apply(diff);
expect(file.readAsStringSync(), 'Modified content\n'); expect(file.readAsStringSync(), 'Modified content\n');
diff.free(); diff.free();
}); });
test('throws when trying to apply diff and error occurs', () {
final nullDiff = Diff(nullptr);
expect(
() => repo.apply(diff: nullDiff),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'diff'",
),
),
);
});
test('successfully creates patch from entry index in diff', () { test('successfully creates patch from entry index in diff', () {
final diff = Diff.parse(patchText); final diff = Diff.parse(patchText);
final patch = Patch.fromDiff(diff: diff, index: 0); final patch = Patch.fromDiff(diff: diff, index: 0);
@ -279,6 +341,34 @@ index e69de29..c217c63 100644
newTree.free(); newTree.free();
}); });
test('throws when trying to find similar entries and error occurs', () {
final nullDiff = Diff(nullptr);
expect(
() => nullDiff.findSimilar(),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'diff'",
),
),
);
});
test('throws when trying to get patch Oid and error occurs', () {
final nullDiff = Diff(nullptr);
expect(
() => nullDiff.patchOid,
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'diff'",
),
),
);
});
test('returns deltas', () { test('returns deltas', () {
final index = repo.index; final index = repo.index;
final diff = index.diffToWorkdir(); final diff = index.diffToWorkdir();
@ -294,10 +384,7 @@ index e69de29..c217c63 100644
diff.deltas[0].oldFile.oid.sha, diff.deltas[0].oldFile.oid.sha,
'e69de29bb2d1d6434b8b29ae775ad8c2e48c5391', 'e69de29bb2d1d6434b8b29ae775ad8c2e48c5391',
); );
expect( expect(diff.deltas[0].newFile.oid.sha, '0' * 40);
diff.deltas[0].newFile.oid.sha,
'0000000000000000000000000000000000000000',
);
expect(diff.deltas[2].oldFile.size, 17); expect(diff.deltas[2].oldFile.size, 17);
@ -316,7 +403,26 @@ index e69de29..c217c63 100644
index.free(); index.free();
}); });
test('returns deltas', () { test('throws when trying to get delta with invalid index', () {
final index = repo.index;
final diff = index.diffToWorkdir();
expect(
() => diff.deltas[-1],
throwsA(
isA<RangeError>().having(
(e) => e.message,
'error',
"Invalid value",
),
),
);
diff.free();
index.free();
});
test('returns patches', () {
final index = repo.index; final index = repo.index;
final diff = index.diffToWorkdir(); final diff = index.diffToWorkdir();
final patches = diff.patches; final patches = diff.patches;
@ -346,6 +452,34 @@ index e69de29..c217c63 100644
index.free(); index.free();
}); });
test('throws when trying to get stats and error occurs', () {
final nullDiff = Diff(nullptr);
expect(
() => nullDiff.stats,
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'diff'",
),
),
);
});
test('throws when trying to print stats and error occurs', () {
final nullStats = DiffStats(nullptr);
expect(
() => nullStats.print(format: {GitDiffStats.full}, width: 80),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'stats'",
),
),
);
});
test('returns patch diff string', () { test('returns patch diff string', () {
final diff = Diff.parse(patchText); final diff = Diff.parse(patchText);

View file

@ -1,3 +1,4 @@
import 'dart:ffi';
import 'dart:io'; import 'dart:io';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:libgit2dart/libgit2dart.dart'; import 'package:libgit2dart/libgit2dart.dart';
@ -74,6 +75,19 @@ void main() {
expect(index.length, 0); expect(index.length, 0);
}); });
test('throws when trying to clear the contents and error occurs', () {
expect(
() => Index(nullptr).clear(),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'index'",
),
),
);
});
group('add()', () { group('add()', () {
test('successfully adds with provided IndexEntry', () { test('successfully adds with provided IndexEntry', () {
final entry = index['file']; final entry = index['file'];
@ -90,14 +104,45 @@ void main() {
}); });
test('throws if file not found at provided path', () { test('throws if file not found at provided path', () {
expect(() => index.add('not_there'), throwsA(isA<LibGit2Error>())); expect(
() => index.add('not_there'),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"could not find '${repo.workdir}not_there' to stat: No such file or directory",
),
),
);
});
test('throws if provided IndexEntry is invalid', () {
expect(
() => index.add(IndexEntry(nullptr)),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'source_entry && source_entry->path'",
),
),
);
}); });
test('throws if index of bare repository', () { test('throws if index of bare repository', () {
final bare = Repository.open('test/assets/empty_bare.git'); final bare = Repository.open('test/assets/empty_bare.git');
final bareIndex = bare.index; final bareIndex = bare.index;
expect(() => bareIndex.add('config'), throwsA(isA<LibGit2Error>())); expect(
() => bareIndex.add('config'),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"cannot create blob from file. This operation is not allowed against bare repositories.",
),
),
);
bareIndex.free(); bareIndex.free();
bare.free(); bare.free();
@ -126,6 +171,25 @@ void main() {
expect(index.length, 1); expect(index.length, 1);
expect(index['feature_file'].sha, featureFileSha); expect(index['feature_file'].sha, featureFileSha);
}); });
test('throws when trying to addAll in bare repository', () {
final bare = Repository.open('test/assets/empty_bare.git');
final bareIndex = bare.index;
expect(
() => bareIndex.addAll([]),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"cannot index add all. This operation is not allowed against bare repositories.",
),
),
);
bareIndex.free();
bare.free();
});
}); });
test('writes to disk', () { test('writes to disk', () {
@ -148,6 +212,19 @@ void main() {
expect(index.find('feature_file'), false); expect(index.find('feature_file'), false);
}); });
test('throws when trying to remove entry with invalid path', () {
expect(
() => index.remove('invalid'),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"index does not contain invalid at stage 0",
),
),
);
});
test('removes all entries with matching pathspec', () { test('removes all entries with matching pathspec', () {
expect(index.find('file'), true); expect(index.find('file'), true);
expect(index.find('feature_file'), true); expect(index.find('feature_file'), true);
@ -177,11 +254,51 @@ void main() {
expect(oid.sha, 'a8ae3dd59e6e1802c6f78e05e301bfd57c9f334f'); expect(oid.sha, 'a8ae3dd59e6e1802c6f78e05e301bfd57c9f334f');
}); });
test('throws when trying to write tree to invalid repository', () {
expect(
() => index.writeTree(Repository(nullptr)),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'repo'",
),
),
);
});
test('throws when trying to write tree while index have conflicts', () {
final tmpDir = setupRepo(Directory('test/assets/mergerepo/'));
final repo = Repository.open(tmpDir.path);
final conflictBranch = repo.lookupBranch(name: 'conflict-branch');
final index = repo.index;
repo.merge(conflictBranch.target);
expect(
() => index.writeTree(),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"cannot create a tree from a not fully merged index.",
),
),
);
conflictBranch.free();
index.free();
repo.free();
tmpDir.deleteSync(recursive: true);
});
test('returns conflicts with ancestor, our and their present', () { test('returns conflicts with ancestor, our and their present', () {
final repoDir = setupRepo(Directory('test/assets/mergerepo/')); final repoDir = setupRepo(Directory('test/assets/mergerepo/'));
final conflictRepo = Repository.open(repoDir.path); final conflictRepo = Repository.open(repoDir.path);
final conflictBranch = conflictRepo.lookupBranch('ancestor-conflict'); final conflictBranch = conflictRepo.lookupBranch(
name: 'ancestor-conflict',
);
conflictRepo.checkout(refName: 'refs/heads/feature'); conflictRepo.checkout(refName: 'refs/heads/feature');
@ -204,7 +321,7 @@ void main() {
final repoDir = setupRepo(Directory('test/assets/mergerepo/')); final repoDir = setupRepo(Directory('test/assets/mergerepo/'));
final conflictRepo = Repository.open(repoDir.path); final conflictRepo = Repository.open(repoDir.path);
final conflictBranch = conflictRepo.lookupBranch('conflict-branch'); final conflictBranch = conflictRepo.lookupBranch(name: 'conflict-branch');
conflictRepo.merge(conflictBranch.target); conflictRepo.merge(conflictBranch.target);
@ -225,7 +342,9 @@ void main() {
final repoDir = setupRepo(Directory('test/assets/mergerepo/')); final repoDir = setupRepo(Directory('test/assets/mergerepo/'));
final conflictRepo = Repository.open(repoDir.path); final conflictRepo = Repository.open(repoDir.path);
final conflictBranch = conflictRepo.lookupBranch('ancestor-conflict'); final conflictBranch = conflictRepo.lookupBranch(
name: 'ancestor-conflict',
);
conflictRepo.checkout(refName: 'refs/heads/our-conflict'); conflictRepo.checkout(refName: 'refs/heads/our-conflict');
@ -248,7 +367,7 @@ void main() {
final repoDir = setupRepo(Directory('test/assets/mergerepo/')); final repoDir = setupRepo(Directory('test/assets/mergerepo/'));
final conflictRepo = Repository.open(repoDir.path); final conflictRepo = Repository.open(repoDir.path);
final conflictBranch = conflictRepo.lookupBranch('their-conflict'); final conflictBranch = conflictRepo.lookupBranch(name: 'their-conflict');
conflictRepo.checkout(refName: 'refs/heads/feature'); conflictRepo.checkout(refName: 'refs/heads/feature');
@ -267,6 +386,43 @@ void main() {
repoDir.deleteSync(recursive: true); repoDir.deleteSync(recursive: true);
}); });
test('successfully removes conflicts', () {
final repoDir = setupRepo(Directory('test/assets/mergerepo/'));
final conflictRepo = Repository.open(repoDir.path);
final conflictBranch = conflictRepo.lookupBranch(name: 'conflict-branch');
final index = conflictRepo.index;
conflictRepo.merge(conflictBranch.target);
expect(index.hasConflicts, true);
expect(index.conflicts.length, 1);
final conflictedFile = index.conflicts['conflict_file']!;
conflictedFile.remove();
expect(index.hasConflicts, false);
expect(index.conflicts, isEmpty);
expect(index.conflicts['conflict_file'], null);
index.free();
conflictBranch.free();
conflictRepo.free();
repoDir.deleteSync(recursive: true);
});
test('throws when trying to remove conflict and error occurs', () {
expect(
() => ConflictEntry(index.pointer, 'invalid.path', null, null, null)
.remove(),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"index does not contain invalid.path",
),
),
);
});
test('returns string representation of Index and IndexEntry objects', () { test('returns string representation of Index and IndexEntry objects', () {
final index = repo.index; final index = repo.index;

View file

@ -1,3 +1,4 @@
import 'dart:ffi';
import 'dart:io'; import 'dart:io';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:libgit2dart/libgit2dart.dart'; import 'package:libgit2dart/libgit2dart.dart';
@ -172,6 +173,19 @@ Santa Claus <santa.claus@northpole.xx> <me@company.xx>
mailmap.free(); mailmap.free();
}); });
test('throws when initializing from repository and error occurs', () {
expect(
() => Mailmap.fromRepository(Repository(nullptr)),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'repo'",
),
),
);
});
test('successfully resolves names and emails when mailmap is empty', () { test('successfully resolves names and emails when mailmap is empty', () {
final mailmap = Mailmap.empty(); final mailmap = Mailmap.empty();
@ -207,6 +221,25 @@ Santa Claus <santa.claus@northpole.xx> <me@company.xx>
mailmap.free(); mailmap.free();
}); });
test('throws when trying to add entry with empty replace email', () {
final mailmap = Mailmap.empty();
expect(
() => mailmap.addEntry(
replaceEmail: ' ',
),
throwsA(
isA<ArgumentError>().having(
(e) => e.toString(),
'error',
'Invalid argument: "replaceEmail can\'t be empty"',
),
),
);
mailmap.free();
});
test('successfully resolves signature', () { test('successfully resolves signature', () {
final signature = Signature.create( final signature = Signature.create(
name: 'nick1', name: 'nick1',
@ -225,6 +258,8 @@ Santa Claus <santa.claus@northpole.xx> <me@company.xx>
); );
expect(mailmap.resolveSignature(signature), realSignature); expect(mailmap.resolveSignature(signature), realSignature);
mailmap.free();
}); });
}); });
} }

View file

@ -1,5 +1,6 @@
// ignore_for_file: unnecessary_string_escapes // ignore_for_file: unnecessary_string_escapes
import 'dart:ffi';
import 'dart:io'; import 'dart:io';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:libgit2dart/libgit2dart.dart'; import 'package:libgit2dart/libgit2dart.dart';
@ -22,49 +23,32 @@ void main() {
group('Merge', () { group('Merge', () {
group('analysis', () { group('analysis', () {
test('is up to date when no reference is provided', () { test('is up to date when no reference is provided', () {
final commit = repo.lookupCommit( final result = repo.mergeAnalysis(theirHead: repo['c68ff54']);
repo['c68ff54aabf660fcdd9a2838d401583fe31249e3'],
);
final result = repo.mergeAnalysis(theirHead: commit.oid);
expect(result, [ expect(result, [
{GitMergeAnalysis.upToDate}, {GitMergeAnalysis.upToDate},
GitMergePreference.none, GitMergePreference.none,
]); ]);
expect(repo.status, isEmpty); expect(repo.status, isEmpty);
commit.free();
}); });
test('is up to date for provided ref', () { test('is up to date for provided ref', () {
final commit = repo.lookupCommit(
repo['c68ff54aabf660fcdd9a2838d401583fe31249e3'],
);
final result = repo.mergeAnalysis( final result = repo.mergeAnalysis(
theirHead: commit.oid, theirHead: repo['c68ff54'],
ourRef: 'refs/tags/v0.1', ourRef: 'refs/tags/v0.1',
); );
expect(result[0], {GitMergeAnalysis.upToDate}); expect(result[0], {GitMergeAnalysis.upToDate});
expect(repo.status, isEmpty); expect(repo.status, isEmpty);
commit.free();
}); });
test('is fast forward', () { test('is fast forward', () {
final theirHead = repo.lookupCommit( final ffCommit = repo.lookupCommit(repo['f17d0d4']);
repo['6cbc22e509d72758ab4c8d9f287ea846b90c448b'],
);
final ffCommit = repo.lookupCommit(
repo['f17d0d48eae3aa08cecf29128a35e310c97b3521'],
);
final ffBranch = repo.createBranch( final ffBranch = repo.createBranch(
name: 'ff-branch', name: 'ff-branch',
target: ffCommit, target: ffCommit,
); );
final result = repo.mergeAnalysis( final result = repo.mergeAnalysis(
theirHead: theirHead.oid, theirHead: repo['6cbc22e'],
ourRef: 'refs/heads/${ffBranch.name}', ourRef: 'refs/heads/${ffBranch.name}',
); );
expect( expect(
@ -75,24 +59,17 @@ void main() {
ffBranch.free(); ffBranch.free();
ffCommit.free(); ffCommit.free();
theirHead.free();
}); });
test('is not fast forward and there is no conflicts', () { test('is not fast forward and there is no conflicts', () {
final commit = repo.lookupCommit( final result = repo.mergeAnalysis(theirHead: repo['5aecfa0']);
repo['5aecfa0fb97eadaac050ccb99f03c3fb65460ad4'],
);
final result = repo.mergeAnalysis(theirHead: commit.oid);
expect(result[0], {GitMergeAnalysis.normal}); expect(result[0], {GitMergeAnalysis.normal});
expect(repo.status, isEmpty); expect(repo.status, isEmpty);
commit.free();
}); });
}); });
test('writes conflicts to index', () { test('writes conflicts to index', () {
final conflictBranch = repo.lookupBranch('conflict-branch'); final conflictBranch = repo.lookupBranch(name: 'conflict-branch');
final index = repo.index; final index = repo.index;
final result = repo.mergeAnalysis(theirHead: conflictBranch.target); final result = repo.mergeAnalysis(theirHead: conflictBranch.target);
@ -129,24 +106,6 @@ void main() {
conflictBranch.free(); conflictBranch.free();
}); });
test('successfully removes conflicts', () {
final conflictBranch = repo.lookupBranch('conflict-branch');
final index = repo.index;
repo.merge(conflictBranch.target);
expect(index.hasConflicts, true);
expect(index.conflicts.length, 1);
final conflictedFile = index.conflicts['conflict_file']!;
conflictedFile.remove();
expect(index.hasConflicts, false);
expect(index.conflicts, isEmpty);
expect(index.conflicts['conflict_file'], null);
index.free();
conflictBranch.free();
});
group('merge file from index', () { group('merge file from index', () {
test('successfully merges without ancestor', () { test('successfully merges without ancestor', () {
const diffExpected = """ const diffExpected = """
@ -156,7 +115,7 @@ master conflict edit
conflict branch edit conflict branch edit
>>>>>>> conflict_file >>>>>>> conflict_file
"""; """;
final conflictBranch = repo.lookupBranch('conflict-branch'); final conflictBranch = repo.lookupBranch(name: 'conflict-branch');
final index = repo.index; final index = repo.index;
repo.merge(conflictBranch.target); repo.merge(conflictBranch.target);
@ -184,7 +143,7 @@ Feature edit on feature branch
Another feature edit Another feature edit
>>>>>>> feature_file >>>>>>> feature_file
"""; """;
final conflictBranch = repo.lookupBranch('ancestor-conflict'); final conflictBranch = repo.lookupBranch(name: 'ancestor-conflict');
repo.checkout(refName: 'refs/heads/feature'); repo.checkout(refName: 'refs/heads/feature');
final index = repo.index; final index = repo.index;
repo.merge(conflictBranch.target); repo.merge(conflictBranch.target);
@ -204,16 +163,29 @@ Another feature edit
index.free(); index.free();
conflictBranch.free(); conflictBranch.free();
}); });
test('throws when error occurs', () {
expect(
() => repo.mergeFileFromIndex(
ancestor: null,
ours: IndexEntry(nullptr),
theirs: IndexEntry(nullptr),
),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'ours'",
),
),
);
});
}); });
group('merge commits', () { group('merge commits', () {
test('successfully merges with default values', () { test('successfully merges with default values', () {
final theirCommit = repo.lookupCommit( final theirCommit = repo.lookupCommit(repo['5aecfa0']);
repo['5aecfa0fb97eadaac050ccb99f03c3fb65460ad4'], final ourCommit = repo.lookupCommit(repo['1490545']);
);
final ourCommit = repo.lookupCommit(
repo['14905459d775f3f56a39ebc2ff081163f7da3529'],
);
final mergeIndex = repo.mergeCommits( final mergeIndex = repo.mergeCommits(
ourCommit: ourCommit, ourCommit: ourCommit,
@ -236,12 +208,8 @@ Another feature edit
}); });
test('successfully merges with provided favor', () { test('successfully merges with provided favor', () {
final theirCommit = repo.lookupCommit( final theirCommit = repo.lookupCommit(repo['5aecfa0']);
repo['5aecfa0fb97eadaac050ccb99f03c3fb65460ad4'], final ourCommit = repo.lookupCommit(repo['1490545']);
);
final ourCommit = repo.lookupCommit(
repo['14905459d775f3f56a39ebc2ff081163f7da3529'],
);
final mergeIndex = repo.mergeCommits( final mergeIndex = repo.mergeCommits(
ourCommit: ourCommit, ourCommit: ourCommit,
@ -256,12 +224,8 @@ Another feature edit
}); });
test('successfully merges with provided merge and file flags', () { test('successfully merges with provided merge and file flags', () {
final theirCommit = repo.lookupCommit( final theirCommit = repo.lookupCommit(repo['5aecfa0']);
repo['5aecfa0fb97eadaac050ccb99f03c3fb65460ad4'], final ourCommit = repo.lookupCommit(repo['1490545']);
);
final ourCommit = repo.lookupCommit(
repo['14905459d775f3f56a39ebc2ff081163f7da3529'],
);
final mergeIndex = repo.mergeCommits( final mergeIndex = repo.mergeCommits(
ourCommit: ourCommit, ourCommit: ourCommit,
@ -282,18 +246,54 @@ Another feature edit
ourCommit.free(); ourCommit.free();
theirCommit.free(); theirCommit.free();
}); });
test('throws when error occurs', () {
expect(
() => repo.mergeCommits(
ourCommit: Commit(nullptr),
theirCommit: Commit(nullptr),
),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'commit'",
),
),
);
});
});
test('successfully finds merge base', () {
var base = repo.mergeBase(a: repo['1490545'], b: repo['5aecfa0']);
expect(base.sha, 'fc38877b2552ab554752d9a77e1f48f738cca79b');
base = repo.mergeBase(a: repo['f17d0d4'], b: repo['5aecfa0']);
expect(base.sha, 'f17d0d48eae3aa08cecf29128a35e310c97b3521');
});
test('throws when trying to find merge base for invalid oid', () {
expect(
() => repo.mergeBase(a: repo['0' * 40], b: repo['5aecfa0']),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"odb: cannot read object: null OID cannot exist",
),
),
);
}); });
group('merge trees', () { group('merge trees', () {
test('successfully merges with default values', () { test('successfully merges with default values', () {
final theirCommit = repo.lookupCommit( final theirCommit = repo.lookupCommit(repo['5aecfa0']);
repo['5aecfa0fb97eadaac050ccb99f03c3fb65460ad4'], final ourCommit = repo.lookupCommit(repo['1490545']);
);
final ourCommit = repo.lookupCommit(
repo['14905459d775f3f56a39ebc2ff081163f7da3529'],
);
final baseCommit = repo.lookupCommit( final baseCommit = repo.lookupCommit(
repo.mergeBase(a: ourCommit.oid, b: theirCommit.oid), repo.mergeBase(
a: ourCommit.oid,
b: theirCommit.oid,
),
); );
final theirTree = theirCommit.tree; final theirTree = theirCommit.tree;
final ourTree = ourCommit.tree; final ourTree = ourCommit.tree;
@ -326,14 +326,13 @@ Another feature edit
}); });
test('successfully merges with provided favor', () { test('successfully merges with provided favor', () {
final theirCommit = repo.lookupCommit( final theirCommit = repo.lookupCommit(repo['5aecfa0']);
repo['5aecfa0fb97eadaac050ccb99f03c3fb65460ad4'], final ourCommit = repo.lookupCommit(repo['1490545']);
);
final ourCommit = repo.lookupCommit(
repo['14905459d775f3f56a39ebc2ff081163f7da3529'],
);
final baseCommit = repo.lookupCommit( final baseCommit = repo.lookupCommit(
repo.mergeBase(a: ourCommit.oid, b: theirCommit.oid), repo.mergeBase(
a: ourCommit.oid,
b: theirCommit.oid,
),
); );
final theirTree = theirCommit.tree; final theirTree = theirCommit.tree;
final ourTree = ourCommit.tree; final ourTree = ourCommit.tree;
@ -355,22 +354,60 @@ Another feature edit
ourCommit.free(); ourCommit.free();
theirCommit.free(); theirCommit.free();
}); });
test('throws when error occurs', () {
expect(
() => Repository(nullptr).mergeTrees(
ancestorTree: Tree(nullptr),
ourTree: Tree(nullptr),
theirTree: Tree(nullptr),
),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'repo'",
),
),
);
});
}); });
test('successfully cherry-picks commit', () { test('successfully cherry-picks commit', () {
final cherry = repo.lookupCommit( final cherry = repo.lookupCommit(repo['5aecfa0']);
repo['5aecfa0fb97eadaac050ccb99f03c3fb65460ad4'],
);
repo.cherryPick(cherry); repo.cherryPick(cherry);
expect(repo.state, GitRepositoryState.cherrypick); expect(repo.state, GitRepositoryState.cherrypick);
expect(repo.message, 'add another feature file\n'); expect(repo.message, 'add another feature file\n');
final index = repo.index; final index = repo.index;
expect(index.conflicts, isEmpty); expect(index.conflicts, isEmpty);
// pretend we've done commit // pretend we've done commit
repo.removeMessage(); repo.removeMessage();
expect(() => repo.message, throwsA(isA<LibGit2Error>())); expect(
() => repo.message,
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"could not access message file: No such file or directory",
),
),
);
index.free(); index.free();
}); });
test('throws when error occurs', () {
expect(
() => repo.cherryPick(Commit(nullptr)),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'commit'",
),
),
);
});
}); });
} }

View file

@ -1,3 +1,4 @@
import 'dart:ffi';
import 'dart:io'; import 'dart:io';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:libgit2dart/libgit2dart.dart'; import 'package:libgit2dart/libgit2dart.dart';
@ -43,6 +44,20 @@ void main() {
} }
}); });
test('throws when trying to get list of notes and error occurs', () {
Directory('${repo.workdir}.git/refs/notes').deleteSync(recursive: true);
expect(
() => repo.notes,
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"reference 'refs/notes/commits' not found",
),
),
);
});
test('successfully lookups note', () { test('successfully lookups note', () {
final head = repo.head; final head = repo.head;
final note = repo.lookupNote(annotatedOid: head.target); final note = repo.lookupNote(annotatedOid: head.target);
@ -75,7 +90,25 @@ void main() {
signature.free(); signature.free();
}); });
test('successfully removes note', () { test('throws when trying to create note and error occurs', () {
expect(
() => Repository(nullptr).createNote(
author: Signature(nullptr),
committer: Signature(nullptr),
annotatedOid: repo['0' * 40],
note: '',
),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'repo'",
),
),
);
});
test('successfully deletes note', () {
final signature = repo.defaultSignature; final signature = repo.defaultSignature;
final head = repo.head; final head = repo.head;
@ -87,13 +120,36 @@ void main() {
expect( expect(
() => repo.lookupNote(annotatedOid: head.target), () => repo.lookupNote(annotatedOid: head.target),
throwsA(isA<LibGit2Error>()), throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"note could not be found",
),
),
); );
head.free(); head.free();
signature.free(); signature.free();
}); });
test('throws when trying to delete note and error occurs', () {
expect(
() => Repository(nullptr).deleteNote(
author: Signature(nullptr),
committer: Signature(nullptr),
annotatedOid: repo['0' * 40],
),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'repo'",
),
),
);
});
test('returns string representation of Note object', () { test('returns string representation of Note object', () {
final note = repo.lookupNote(annotatedOid: repo['821ed6e']); final note = repo.lookupNote(annotatedOid: repo['821ed6e']);
expect(note.toString(), contains('Note{')); expect(note.toString(), contains('Note{'));

View file

@ -27,6 +27,20 @@ void main() {
odb.free(); odb.free();
}); });
test('throws when trying to get odb and error occurs', () {
Directory('${repo.workdir}.git/objects/').deleteSync(recursive: true);
expect(
() => repo.odb,
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
contains("failed to load object database"),
),
),
);
});
test('successfully creates new odb with no backends', () { test('successfully creates new odb with no backends', () {
final odb = Odb.create(); final odb = Odb.create();
expect(odb, isA<Odb>()); expect(odb, isA<Odb>());
@ -56,6 +70,23 @@ void main() {
odb.free(); odb.free();
}); });
test('throws when trying to read object and error occurs', () {
final odb = repo.odb;
expect(
() => odb.read(repo['0' * 40]),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"odb: cannot read object: null OID cannot exist",
),
),
);
odb.free();
});
test('returns list of all objects oid\'s in database', () { test('returns list of all objects oid\'s in database', () {
final odb = repo.odb; final odb = repo.odb;
@ -65,6 +96,24 @@ void main() {
odb.free(); odb.free();
}); });
test('throws when trying to get list of all objects and error occurs', () {
final odb = repo.odb;
Directory('${repo.workdir}.git/objects').deleteSync(recursive: true);
expect(
() => odb.objects,
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"object not found - failed to refresh packfiles",
),
),
);
odb.free();
});
test('successfully writes data', () { test('successfully writes data', () {
final odb = repo.odb; final odb = repo.odb;
final oid = odb.write(type: GitObject.blob, data: 'testing'); final oid = odb.write(type: GitObject.blob, data: 'testing');
@ -81,7 +130,31 @@ void main() {
final odb = repo.odb; final odb = repo.odb;
expect( expect(
() => odb.write(type: GitObject.any, data: 'testing'), () => odb.write(type: GitObject.any, data: 'testing'),
throwsA(isA<ArgumentError>()), throwsA(
isA<ArgumentError>().having(
(e) => e.toString(),
'error',
'Invalid argument: "GitObject.any is invalid type"',
),
),
);
odb.free();
});
test('throws when trying to write to disk alternate odb', () {
final odb = Odb.create();
odb.addDiskAlternate('${repo.workdir}.git/objects/');
expect(
() => odb.write(type: GitObject.blob, data: ''),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"cannot write object - unsupported in the loaded odb backends",
),
),
); );
odb.free(); odb.free();

View file

@ -23,13 +23,13 @@ void main() {
group('Oid', () { group('Oid', () {
group('fromSHA()', () { group('fromSHA()', () {
test('initializes successfully', () { test('successfully initializes', () {
final oid = Oid.fromSHA(repo: repo, sha: sha); final oid = Oid.fromSHA(repo: repo, sha: sha);
expect(oid, isA<Oid>()); expect(oid, isA<Oid>());
expect(oid.sha, sha); expect(oid.sha, sha);
}); });
test('initializes successfully from short hex string', () { test('successfully initializes from short hex string', () {
final oid = Oid.fromSHA(repo: repo, sha: sha.substring(0, 5)); final oid = Oid.fromSHA(repo: repo, sha: sha.substring(0, 5));
expect(oid, isA<Oid>()); expect(oid, isA<Oid>());
@ -41,9 +41,22 @@ void main() {
() => Oid.fromSHA(repo: repo, sha: 'sha'), () => Oid.fromSHA(repo: repo, sha: 'sha'),
throwsA( throwsA(
isA<ArgumentError>().having( isA<ArgumentError>().having(
(e) => e.invalidValue, (e) => e.toString(),
'value', 'value',
'sha is not a valid sha hex string', 'Invalid argument: "sha is not a valid sha hex string"',
),
),
);
});
test('throws when sha hex string is invalid', () {
expect(
() => Oid.fromSHA(repo: repo, sha: '0000000'),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"object not found - no match for id prefix (0000000)",
), ),
), ),
); );

View file

@ -1,3 +1,4 @@
import 'dart:ffi';
import 'dart:io'; import 'dart:io';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:libgit2dart/libgit2dart.dart'; import 'package:libgit2dart/libgit2dart.dart';
@ -27,6 +28,19 @@ void main() {
packbuilder.free(); packbuilder.free();
}); });
test('throws when trying to initialize and error occurs', () {
expect(
() => PackBuilder(Repository(nullptr)),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'repo'",
),
),
);
});
test('successfully adds objects', () { test('successfully adds objects', () {
final packbuilder = PackBuilder(repo); final packbuilder = PackBuilder(repo);
final odb = repo.odb; final odb = repo.odb;
@ -41,7 +55,24 @@ void main() {
packbuilder.free(); packbuilder.free();
}); });
test('successfully adds objects recursively', () { test('throws when trying to add object and error occurs', () {
final packbuilder = PackBuilder(repo);
expect(
() => packbuilder.add(Oid(nullptr)),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'oid'",
),
),
);
packbuilder.free();
});
test('successfully adds object recursively', () {
final packbuilder = PackBuilder(repo); final packbuilder = PackBuilder(repo);
final oid = Oid.fromSHA(repo: repo, sha: 'f17d0d48'); final oid = Oid.fromSHA(repo: repo, sha: 'f17d0d48');
@ -51,6 +82,23 @@ void main() {
packbuilder.free(); packbuilder.free();
}); });
test('throws when trying to add object recursively and error occurs', () {
final packbuilder = PackBuilder(repo);
expect(
() => packbuilder.addRecursively(Oid(nullptr)),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'id'",
),
),
);
packbuilder.free();
});
test('successfully sets number of threads', () { test('successfully sets number of threads', () {
final packbuilder = PackBuilder(repo); final packbuilder = PackBuilder(repo);
@ -105,6 +153,23 @@ void main() {
expect(writtenCount, 18); expect(writtenCount, 18);
}); });
test('throws when trying to write pack into invalid path', () {
final packbuilder = PackBuilder(repo);
expect(
() => packbuilder.write('invalid/path'),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
contains('failed to create temporary file'),
),
),
);
packbuilder.free();
});
test('returns string representation of PackBuilder object', () { test('returns string representation of PackBuilder object', () {
final packbuilder = PackBuilder(repo); final packbuilder = PackBuilder(repo);
expect(packbuilder.toString(), contains('PackBuilder{')); expect(packbuilder.toString(), contains('PackBuilder{'));

View file

@ -1,3 +1,4 @@
import 'dart:ffi';
import 'dart:io'; import 'dart:io';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:libgit2dart/libgit2dart.dart'; import 'package:libgit2dart/libgit2dart.dart';
@ -8,8 +9,8 @@ void main() {
late Directory tmpDir; late Directory tmpDir;
const oldBlob = ''; const oldBlob = '';
const newBlob = 'Feature edit\n'; const newBlob = 'Feature edit\n';
late Oid oldBlobID; late Oid oldBlobOid;
late Oid newBlobID; late Oid newBlobOid;
const path = 'feature_file'; const path = 'feature_file';
const blobPatch = """ const blobPatch = """
diff --git a/feature_file b/feature_file diff --git a/feature_file b/feature_file
@ -41,8 +42,8 @@ index e69de29..0000000
setUp(() { setUp(() {
tmpDir = setupRepo(Directory('test/assets/testrepo/')); tmpDir = setupRepo(Directory('test/assets/testrepo/'));
repo = Repository.open(tmpDir.path); repo = Repository.open(tmpDir.path);
oldBlobID = repo['e69de29bb2d1d6434b8b29ae775ad8c2e48c5391']; oldBlobOid = repo['e69de29bb2d1d6434b8b29ae775ad8c2e48c5391'];
newBlobID = repo['9c78c21d6680a7ffebc76f7ac68cacc11d8f48bc']; newBlobOid = repo['9c78c21d6680a7ffebc76f7ac68cacc11d8f48bc'];
}); });
tearDown(() { tearDown(() {
@ -92,8 +93,8 @@ index e69de29..0000000
}); });
test('successfully creates from blobs', () { test('successfully creates from blobs', () {
final a = repo.lookupBlob(oldBlobID); final a = repo.lookupBlob(oldBlobOid);
final b = repo.lookupBlob(newBlobID); final b = repo.lookupBlob(newBlobOid);
final patch = Patch.create( final patch = Patch.create(
a: a, a: a,
b: b, b: b,
@ -107,7 +108,7 @@ index e69de29..0000000
}); });
test('successfully creates from one blob (add)', () { test('successfully creates from one blob (add)', () {
final b = repo.lookupBlob(newBlobID); final b = repo.lookupBlob(newBlobOid);
final patch = Patch.create( final patch = Patch.create(
a: null, a: null,
b: b, b: b,
@ -121,7 +122,7 @@ index e69de29..0000000
}); });
test('successfully creates from one blob (delete)', () { test('successfully creates from one blob (delete)', () {
final a = repo.lookupBlob(oldBlobID); final a = repo.lookupBlob(oldBlobOid);
final patch = Patch.create( final patch = Patch.create(
a: a, a: a,
b: null, b: null,
@ -135,7 +136,7 @@ index e69de29..0000000
}); });
test('successfully creates from blob and buffer', () { test('successfully creates from blob and buffer', () {
final a = repo.lookupBlob(oldBlobID); final a = repo.lookupBlob(oldBlobOid);
final patch = Patch.create( final patch = Patch.create(
a: a, a: a,
b: newBlob, b: newBlob,
@ -159,7 +160,13 @@ index e69de29..0000000
aPath: 'file', aPath: 'file',
bPath: 'file', bPath: 'file',
), ),
throwsA(isA<ArgumentError>()), throwsA(
isA<ArgumentError>().having(
(e) => e.toString(),
'error',
"Invalid argument(s): Provided argument(s) is not Blob or String",
),
),
); );
expect( expect(
@ -169,12 +176,44 @@ index e69de29..0000000
aPath: 'file', aPath: 'file',
bPath: 'file', bPath: 'file',
), ),
throwsA(isA<ArgumentError>()), throwsA(
isA<ArgumentError>().having(
(e) => e.toString(),
'error',
"Invalid argument(s): Provided argument(s) is not Blob or String",
),
),
); );
commit.free(); commit.free();
}); });
test('throws when trying to create from diff and error occurs', () {
expect(
() => Patch.fromDiff(diff: Diff(nullptr), index: 0),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'diff'",
),
),
);
});
test('throws when trying to text of patch and error occurs', () {
expect(
() => Patch(nullptr, nullptr, nullptr).text,
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'patch'",
),
),
);
});
test('returns string representation of Patch object', () { test('returns string representation of Patch object', () {
final patch = Patch.create( final patch = Patch.create(
a: oldBlob, a: oldBlob,

View file

@ -29,7 +29,16 @@ void main() {
final feature = repo.lookupReference('refs/heads/feature'); final feature = repo.lookupReference('refs/heads/feature');
repo.checkout(refName: feature.name); repo.checkout(refName: feature.name);
expect(() => repo.index['.gitignore'], throwsA(isA<ArgumentError>())); expect(
() => repo.index['.gitignore'],
throwsA(
isA<ArgumentError>().having(
(e) => e.toString(),
'error',
'Invalid argument: ".gitignore was not found"',
),
),
);
final rebase = Rebase.init( final rebase = Rebase.init(
repo: repo, repo: repo,
@ -62,6 +71,38 @@ void main() {
signature.free(); signature.free();
}); });
test('successfully performs rebase without branch provided', () {
final signature = repo.defaultSignature;
final feature = repo.lookupReference('refs/heads/feature');
final rebase = Rebase.init(
repo: repo,
onto: feature.target,
);
final operationsCount = rebase.operationsCount;
expect(operationsCount, 3);
for (var i = 0; i < operationsCount; i++) {
final operation = rebase.next();
expect(operation.type, GitRebaseOperation.pick);
expect(operation.oid.sha, shas[i]);
expect(operation.toString(), contains('RebaseOperation{'));
rebase.commit(
committer: signature,
author: signature,
message: 'rebase message',
);
}
rebase.finish();
rebase.free();
feature.free();
signature.free();
});
test('successfully performs rebase with provided upstream', () { test('successfully performs rebase with provided upstream', () {
final signature = repo.defaultSignature; final signature = repo.defaultSignature;
final master = repo.lookupReference('refs/heads/master'); final master = repo.lookupReference('refs/heads/master');
@ -71,13 +112,18 @@ void main() {
repo.checkout(refName: feature.name); repo.checkout(refName: feature.name);
expect( expect(
() => repo.index['conflict_file'], () => repo.index['conflict_file'],
throwsA(isA<ArgumentError>()), throwsA(
isA<ArgumentError>().having(
(e) => e.toString(),
'error',
'Invalid argument: "conflict_file was not found"',
),
),
); );
final rebase = Rebase.init( final rebase = Rebase.init(
repo: repo, repo: repo,
branch: master.target, branch: master.target,
onto: feature.target,
upstream: startCommit.oid, upstream: startCommit.oid,
); );
@ -99,6 +145,21 @@ void main() {
signature.free(); signature.free();
}); });
test(
'throws when trying to initialize rebase without upstream and onto provided',
() {
expect(
() => Rebase.init(repo: repo),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'upstream || onto'",
),
),
);
});
test('stops when there is conflicts', () { test('stops when there is conflicts', () {
final signature = repo.defaultSignature; final signature = repo.defaultSignature;
final master = repo.lookupReference('refs/heads/master'); final master = repo.lookupReference('refs/heads/master');
@ -118,7 +179,46 @@ void main() {
expect(repo.state, GitRepositoryState.rebaseMerge); expect(repo.state, GitRepositoryState.rebaseMerge);
expect( expect(
() => rebase.commit(committer: signature), () => rebase.commit(committer: signature),
throwsA(isA<LibGit2Error>()), throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
'unstaged changes exist in workdir',
),
),
);
rebase.free();
conflict.free();
master.free();
signature.free();
});
test('throws when trying to perfrom next rebase operation and error occurs',
() {
final signature = repo.defaultSignature;
final master = repo.lookupReference('refs/heads/master');
final conflict = repo.lookupReference('refs/heads/conflict-branch');
repo.checkout(refName: conflict.name);
final rebase = Rebase.init(
repo: repo,
branch: master.target,
onto: conflict.target,
);
expect(rebase.operationsCount, 1);
rebase.next(); // repo now have conflicts
expect(
() => rebase.next(),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"object not found - failed to find pack entry (790b86f5fb50db485586370f27c5f90bada97d83)",
),
),
); );
rebase.free(); rebase.free();

View file

@ -1,3 +1,4 @@
import 'dart:ffi';
import 'dart:io'; import 'dart:io';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:libgit2dart/libgit2dart.dart'; import 'package:libgit2dart/libgit2dart.dart';
@ -33,6 +34,19 @@ void main() {
); );
}); });
test('throws when trying to get a list of references and error occurs', () {
expect(
() => Repository(nullptr).references,
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'repo'",
),
),
);
});
test('returns correct type of reference', () { test('returns correct type of reference', () {
final head = repo.head; final head = repo.head;
expect(head.type, ReferenceType.direct); expect(head.type, ReferenceType.direct);
@ -55,6 +69,19 @@ void main() {
ref.free(); ref.free();
}); });
test('throws when trying to resolve invalid reference', () {
expect(
() => Reference(nullptr).target,
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid reference",
),
),
);
});
test('returns the full name', () { test('returns the full name', () {
final head = repo.head; final head = repo.head;
expect(head.name, 'refs/heads/master'); expect(head.name, 'refs/heads/master');
@ -154,7 +181,13 @@ void main() {
name: 'refs/tags/invalid', name: 'refs/tags/invalid',
target: '78b', target: '78b',
), ),
throwsA(isA<LibGit2Error>()), throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"the given reference name '78b' is not valid",
),
),
); );
expect( expect(
@ -162,7 +195,13 @@ void main() {
name: 'refs/tags/invalid', name: 'refs/tags/invalid',
target: 0, target: 0,
), ),
throwsA(isA<ArgumentError>()), throwsA(
isA<ArgumentError>().having(
(e) => e.toString(),
'error',
'Invalid argument: "0 must be either Oid or String reference name"',
),
),
); );
}); });
@ -172,7 +211,13 @@ void main() {
name: 'refs/tags/invalid~', name: 'refs/tags/invalid~',
target: repo[lastCommit], target: repo[lastCommit],
), ),
throwsA(isA<LibGit2Error>()), throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"the given reference name 'refs/tags/invalid~' is not valid",
),
),
); );
}); });
@ -205,7 +250,14 @@ void main() {
name: 'refs/tags/test', name: 'refs/tags/test',
target: repo[lastCommit], target: repo[lastCommit],
), ),
throwsA(isA<LibGit2Error>()), throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"failed to write reference 'refs/tags/test': a reference with that "
"name already exists.",
),
),
); );
ref.free(); ref.free();
@ -255,7 +307,14 @@ void main() {
name: 'refs/tags/exists', name: 'refs/tags/exists',
target: 'refs/heads/master', target: 'refs/heads/master',
), ),
throwsA(isA<LibGit2Error>()), throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"failed to write reference 'refs/tags/exists': a reference with that "
"name already exists.",
),
),
); );
ref.free(); ref.free();
@ -267,7 +326,13 @@ void main() {
name: 'refs/tags/invalid~', name: 'refs/tags/invalid~',
target: 'refs/heads/master', target: 'refs/heads/master',
), ),
throwsA(isA<LibGit2Error>()), throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"the given reference name 'refs/tags/invalid~' is not valid",
),
),
); );
}); });
@ -293,15 +358,10 @@ void main() {
}); });
test('successfully deletes reference', () { test('successfully deletes reference', () {
final ref = repo.createReference( expect(repo.references, contains('refs/tags/v0.1'));
name: 'refs/tags/test',
target: repo[lastCommit],
);
expect(repo.references, contains('refs/tags/test'));
repo.deleteReference('refs/tags/test'); repo.deleteReference('refs/tags/v0.1');
expect(repo.references, isNot(contains('refs/tags/test'))); expect(repo.references, isNot(contains('refs/tags/v0.1')));
ref.free();
}); });
group('finds', () { group('finds', () {
@ -314,7 +374,13 @@ void main() {
test('throws when error occured', () { test('throws when error occured', () {
expect( expect(
() => repo.lookupReference('refs/heads/not/there'), () => repo.lookupReference('refs/heads/not/there'),
throwsA(isA<LibGit2Error>()), throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"reference 'refs/heads/not/there' not found",
),
),
); );
}); });
}); });
@ -368,11 +434,35 @@ void main() {
final ref = repo.lookupReference('HEAD'); final ref = repo.lookupReference('HEAD');
expect( expect(
() => ref.setTarget(target: 'refs/heads/invalid~'), () => ref.setTarget(target: 'refs/heads/invalid~'),
throwsA(isA<LibGit2Error>()), throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"the given reference name 'refs/heads/invalid~' is not valid",
),
),
); );
expect(
() => ref.setTarget(target: Oid(nullptr)),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'id'",
),
),
);
expect( expect(
() => ref.setTarget(target: 0), () => ref.setTarget(target: 0),
throwsA(isA<ArgumentError>()), throwsA(
isA<ArgumentError>().having(
(e) => e.toString(),
'error',
'Invalid argument: "0 must be either Oid or String reference name"',
),
),
); );
ref.free(); ref.free();
@ -497,6 +587,19 @@ void main() {
ref.free(); ref.free();
}); });
test('throws when trying to peel and error occurs', () {
expect(
() => Reference(nullptr).peel(),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'ref'",
),
),
);
});
test('successfully compresses references', () { test('successfully compresses references', () {
final packedRefsFile = File('${tmpDir.path}/.git/packed-refs'); final packedRefsFile = File('${tmpDir.path}/.git/packed-refs');
expect(packedRefsFile.existsSync(), false); expect(packedRefsFile.existsSync(), false);
@ -509,6 +612,19 @@ void main() {
expect(newRefs, oldRefs); expect(newRefs, oldRefs);
}); });
test('throws when trying to compress and error occurs', () {
expect(
() => Reference.compress(Repository(nullptr)),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'repo'",
),
),
);
});
test('returns string representation of Reference object', () { test('returns string representation of Reference object', () {
final ref = repo.lookupReference('refs/heads/master'); final ref = repo.lookupReference('refs/heads/master');
expect(ref.toString(), contains('Reference{')); expect(ref.toString(), contains('Reference{'));

View file

@ -93,5 +93,18 @@ void main() {
branch.free(); branch.free();
} }
}); });
test('throws when trying to prune remote refs and error occurs', () {
expect(
() => remote.prune(),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"this remote has never connected",
),
),
);
});
}); });
} }

View file

@ -68,6 +68,24 @@ void main() {
remote.free(); remote.free();
}); });
test('throws when trying to create with fetchspec with invalid remote name',
() {
expect(
() => repo.createRemote(
name: '',
url: '',
fetch: '',
),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"'' is not a valid remote name.",
),
),
);
});
test('successfully deletes', () { test('successfully deletes', () {
final remote = repo.createRemote(name: 'upstream', url: remoteUrl); final remote = repo.createRemote(name: 'upstream', url: remoteUrl);
expect(repo.remotes.length, 2); expect(repo.remotes.length, 2);
@ -78,6 +96,19 @@ void main() {
remote.free(); remote.free();
}); });
test('throws when trying to delete non existing remote', () {
expect(
() => repo.deleteRemote('not/there'),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"remote 'not/there' does not exist",
),
),
);
});
test('successfully renames', () { test('successfully renames', () {
final remote = repo.lookupRemote(remoteName); final remote = repo.lookupRemote(remoteName);
@ -92,10 +123,31 @@ void main() {
remote.free(); remote.free();
}); });
test('returns list of non-default refspecs that cannot be renamed', () {
final remote = repo.createRemote(
name: 'upstream',
url: remoteUrl,
fetch: '+refs/*:refs/*',
);
expect(
repo.renameRemote(oldName: remote.name, newName: 'renamed'),
['+refs/*:refs/*'],
);
remote.free();
});
test('throws when renaming with invalid names', () { test('throws when renaming with invalid names', () {
expect( expect(
() => repo.renameRemote(oldName: '', newName: ''), () => repo.renameRemote(oldName: '', newName: ''),
throwsA(isA<LibGit2Error>()), throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"'' is not a valid remote name.",
),
),
); );
}); });
@ -165,6 +217,36 @@ void main() {
remote.free(); remote.free();
}); });
test('throws when trying to transform refspec with invalid reference name',
() {
final remote = repo.lookupRemote('origin');
final refspec = remote.getRefspec(0);
expect(
() => refspec.transform('invalid/name'),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"ref 'invalid/name' doesn't match the source",
),
),
);
expect(
() => refspec.rTransform('invalid/name'),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"ref 'invalid/name' doesn't match the destination",
),
),
);
remote.free();
});
test('successfully adds fetch refspec', () { test('successfully adds fetch refspec', () {
Remote.addFetch( Remote.addFetch(
repo: repo, repo: repo,
@ -184,6 +266,23 @@ void main() {
remote.free(); remote.free();
}); });
test('throws when trying to add fetch refspec for invalid remote name', () {
expect(
() => Remote.addFetch(
repo: repo,
remote: '',
refspec: '',
),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"'' is not a valid remote name.",
),
),
);
});
test('successfully adds push refspec', () { test('successfully adds push refspec', () {
Remote.addPush( Remote.addPush(
repo: repo, repo: repo,
@ -197,6 +296,23 @@ void main() {
remote.free(); remote.free();
}); });
test('throws when trying to add push refspec for invalid remote name', () {
expect(
() => Remote.addPush(
repo: repo,
remote: '',
refspec: '',
),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"'' is not a valid remote name.",
),
),
);
});
test('successfully returns remote repo\'s reference list', () { test('successfully returns remote repo\'s reference list', () {
Remote.setUrl( Remote.setUrl(
repo: repo, repo: repo,
@ -218,15 +334,42 @@ void main() {
remote.free(); remote.free();
}); });
test(
'throws when trying to get remote repo\'s reference list with invalid url',
() {
Remote.setUrl(repo: repo, remote: 'libgit2', url: 'invalid');
final remote = repo.lookupRemote('libgit2');
expect(
() => remote.ls(),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"unsupported URL protocol",
),
),
);
remote.free();
});
test('successfully fetches data', () { test('successfully fetches data', () {
Remote.setUrl( Remote.setUrl(
repo: repo, repo: repo,
remote: 'libgit2', remote: 'libgit2',
url: 'https://github.com/libgit2/TestGitRepository', url: 'https://github.com/libgit2/TestGitRepository',
); );
Remote.addFetch(
repo: repo,
remote: 'libgit2',
refspec: '+refs/heads/*:refs/remotes/origin/*',
);
final remote = repo.lookupRemote('libgit2'); final remote = repo.lookupRemote('libgit2');
final stats = remote.fetch(); final stats = remote.fetch(
refspecs: ['+refs/heads/*:refs/remotes/origin/*'],
);
expect(stats.totalObjects, 69); expect(stats.totalObjects, 69);
expect(stats.indexedObjects, 69); expect(stats.indexedObjects, 69);
@ -240,6 +383,84 @@ void main() {
remote.free(); remote.free();
}); });
test('successfully fetches data with proxy set to auto', () {
Remote.setUrl(
repo: repo,
remote: 'libgit2',
url: 'https://github.com/libgit2/TestGitRepository',
);
Remote.addFetch(
repo: repo,
remote: 'libgit2',
refspec: '+refs/heads/*:refs/remotes/origin/*',
);
final remote = repo.lookupRemote('libgit2');
final stats = remote.fetch(
refspecs: ['+refs/heads/*:refs/remotes/origin/*'],
proxy: 'auto',
);
expect(stats.totalObjects, 69);
expect(stats.indexedObjects, 69);
expect(stats.receivedObjects, 69);
expect(stats.localObjects, 0);
expect(stats.totalDeltas, 3);
expect(stats.indexedDeltas, 3);
expect(stats.receivedBytes, 0);
expect(stats.toString(), contains('TransferProgress{'));
remote.free();
});
test('uses specified proxy for fetch', () {
Remote.setUrl(
repo: repo,
remote: 'libgit2',
url: 'https://github.com/libgit2/TestGitRepository',
);
Remote.addFetch(
repo: repo,
remote: 'libgit2',
refspec: '+refs/heads/*:refs/remotes/origin/*',
);
final remote = repo.lookupRemote('libgit2');
expect(
() => remote.fetch(
refspecs: ['+refs/heads/*:refs/remotes/origin/*'],
proxy: 'https://1.1.1.1',
),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"proxy returned unexpected status: 400",
),
),
);
remote.free();
});
test('throws when trying to fetch data with invalid url', () {
Remote.setUrl(repo: repo, remote: 'libgit2', url: 'https://wrong.url');
final remote = repo.lookupRemote('libgit2');
expect(
() => remote.fetch(),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"failed to resolve address for wrong.url: Name or service not known",
),
),
);
remote.free();
});
test('successfully fetches data with provided transfer progress callback', test('successfully fetches data with provided transfer progress callback',
() { () {
Remote.setUrl( Remote.setUrl(
@ -300,20 +521,20 @@ Total 69 (delta 0), reused 1 (delta 0), pack-reused 68
url: 'https://github.com/libgit2/TestGitRepository', url: 'https://github.com/libgit2/TestGitRepository',
); );
final remote = repo.lookupRemote('libgit2'); final remote = repo.lookupRemote('libgit2');
const tipsExpected = [ final tipsExpected = [
{ {
'refname': 'refs/tags/annotated_tag', 'refname': 'refs/tags/annotated_tag',
'oldSha': '0000000000000000000000000000000000000000', 'oldSha': '0' * 40,
'newSha': 'd96c4e80345534eccee5ac7b07fc7603b56124cb', 'newSha': 'd96c4e80345534eccee5ac7b07fc7603b56124cb',
}, },
{ {
'refname': 'refs/tags/blob', 'refname': 'refs/tags/blob',
'oldSha': '0000000000000000000000000000000000000000', 'oldSha': '0' * 40,
'newSha': '55a1a760df4b86a02094a904dfa511deb5655905' 'newSha': '55a1a760df4b86a02094a904dfa511deb5655905'
}, },
{ {
'refname': 'refs/tags/commit_tree', 'refname': 'refs/tags/commit_tree',
'oldSha': '0000000000000000000000000000000000000000', 'oldSha': '0' * 40,
'newSha': '8f50ba15d49353813cc6e20298002c0d17b0a9ee', 'newSha': '8f50ba15d49353813cc6e20298002c0d17b0a9ee',
}, },
]; ];
@ -370,5 +591,23 @@ Total 69 (delta 0), reused 1 (delta 0), pack-reused 68
originRepo.free(); originRepo.free();
originDir.delete(recursive: true); originDir.delete(recursive: true);
}); });
test('throws when trying to push to invalid url', () {
Remote.setUrl(repo: repo, remote: 'libgit2', url: 'https://wrong.url');
final remote = repo.lookupRemote('libgit2');
expect(
() => remote.push(refspecs: ['refs/heads/master']),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"failed to resolve address for wrong.url: Name or service not known",
),
),
);
remote.free();
});
}); });
} }

View file

@ -1,3 +1,4 @@
import 'dart:ffi';
import 'dart:io'; import 'dart:io';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:libgit2dart/libgit2dart.dart'; import 'package:libgit2dart/libgit2dart.dart';
@ -80,6 +81,19 @@ void main() {
expect(repo.isEmpty, true); expect(repo.isEmpty, true);
}); });
test('throws when checking if it is empty and error occurs', () {
expect(
() => Repository(nullptr).isEmpty,
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'repo'",
),
),
);
});
test('checks if head is detached', () { test('checks if head is detached', () {
expect(repo.isHeadDetached, false); expect(repo.isHeadDetached, false);
}); });

View file

@ -1,3 +1,4 @@
import 'dart:ffi';
import 'dart:io'; import 'dart:io';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:libgit2dart/libgit2dart.dart'; import 'package:libgit2dart/libgit2dart.dart';
@ -93,6 +94,58 @@ void main() {
tmpWorkDir.deleteSync(); tmpWorkDir.deleteSync();
}); });
test('throws when trying to set working directory to invalid', () {
expect(
() => repo.setWorkdir(path: 'invalid/path'),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"failed to resolve path 'invalid/path': No such file or directory",
),
),
);
});
test('throws when trying to get head and error occurs', () {
File('${repo.workdir}.git/HEAD').deleteSync();
expect(
() => repo.head,
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"reference 'HEAD' not found",
),
),
);
expect(
() => repo.isHeadDetached,
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"reference 'HEAD' not found",
),
),
);
});
test('throws when trying to check if branch is unborn and error occurs',
() {
File('${repo.workdir}.git/HEAD').deleteSync();
expect(
() => repo.isBranchUnborn,
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"reference 'HEAD' not found",
),
),
);
});
group('setHead', () { group('setHead', () {
late Reference head; late Reference head;
@ -122,7 +175,39 @@ void main() {
}); });
test('throws when target is invalid', () { test('throws when target is invalid', () {
expect(() => repo.setHead(0), throwsA(isA<ArgumentError>())); expect(
() => repo.setHead(0),
throwsA(
isA<ArgumentError>().having(
(e) => e.toString(),
'error',
'Invalid argument: "0 must be either Oid or String reference name"',
),
),
);
});
test('throws when error occurs', () {
expect(
() => Repository(nullptr).setHead('refs/heads/feature'),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'repo'",
),
),
);
expect(
() => Repository(nullptr).setHead(repo['0' * 40]),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'repo'",
),
),
);
}); });
}); });
@ -209,6 +294,23 @@ void main() {
index.free(); index.free();
}); });
test('throws when trying to get status of bare repository', () {
final bare = Repository.open('test/assets/empty_bare.git');
expect(
() => bare.status,
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"cannot status. This operation is not allowed against bare repositories.",
),
),
);
bare.free();
});
test('cleans up state', () { test('cleans up state', () {
expect(repo.state, GitRepositoryState.none); expect(repo.state, GitRepositoryState.none);
final commit = repo.lookupCommit(repo['5aecfa0']); final commit = repo.lookupCommit(repo['5aecfa0']);
@ -221,6 +323,19 @@ void main() {
commit.free(); commit.free();
}); });
test('throws when trying to clean up state and error occurs', () {
expect(
() => Repository(nullptr).stateCleanup(),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'repo'",
),
),
);
});
test('returns status of a single file for provided path', () { test('returns status of a single file for provided path', () {
final index = repo.index; final index = repo.index;
index.remove('file'); index.remove('file');
@ -236,7 +351,13 @@ void main() {
test('throws when checking status of a single file for invalid path', () { test('throws when checking status of a single file for invalid path', () {
expect( expect(
() => repo.statusFile('not-there'), () => repo.statusFile('not-there'),
throwsA(isA<LibGit2Error>()), throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"attempt to get status of nonexistent file 'not-there'",
),
),
); );
}); });
@ -269,24 +390,38 @@ void main() {
}); });
test('checks if commit is a descendant of another commit', () { test('checks if commit is a descendant of another commit', () {
final commit1 = repo.lookupCommit(repo['821ed6e8']); final commit1 = repo['821ed6e8'];
final commit2 = repo.lookupCommit(repo['78b8bf12']); final commit2 = repo['78b8bf12'];
expect( expect(
repo.descendantOf(commit: commit1.oid, ancestor: commit2.oid), repo.descendantOf(commit: commit1, ancestor: commit2),
true, true,
); );
expect( expect(
repo.descendantOf(commit: commit1.oid, ancestor: commit1.oid), repo.descendantOf(commit: commit1, ancestor: commit1),
false, false,
); );
expect( expect(
repo.descendantOf(commit: commit2.oid, ancestor: commit1.oid), repo.descendantOf(commit: commit2, ancestor: commit1),
false, false,
); );
});
commit1.free(); test('throws when trying to check if commit is descendant and error occurs',
commit2.free(); () {
final commit1 = repo['821ed6e8'];
final commit2 = repo['78b8bf12'];
final nullRepo = Repository(nullptr);
expect(
() => nullRepo.descendantOf(commit: commit1, ancestor: commit2),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'repo'",
),
),
);
}); });
test('returns number of ahead behind commits', () { test('returns number of ahead behind commits', () {

View file

@ -35,6 +35,29 @@ void main() {
initCommit.free(); initCommit.free();
}); });
test('.single() throws when spec string not found or invalid', () {
expect(
() => repo.revParseSingle('invalid'),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"revspec 'invalid' not found",
),
),
);
expect(
() => repo.revParseSingle(''),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"failed to parse revision specifier - Invalid pattern ''",
),
),
);
});
test('.ext() returns commit and reference', () { test('.ext() returns commit and reference', () {
final masterRef = repo.lookupReference('refs/heads/master'); final masterRef = repo.lookupReference('refs/heads/master');
var headParse = repo.revParseExt('master'); var headParse = repo.revParseExt('master');
@ -70,6 +93,29 @@ void main() {
headParse.object.free(); headParse.object.free();
}); });
test('.ext() throws when spec string not found or invalid', () {
expect(
() => repo.revParseExt('invalid'),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"revspec 'invalid' not found",
),
),
);
expect(
() => repo.revParseExt(''),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"failed to parse revision specifier - Invalid pattern ''",
),
),
);
});
test( test(
'.range returns revspec with correct fields values based on provided spec', '.range returns revspec with correct fields values based on provided spec',
() { () {
@ -108,12 +154,23 @@ void main() {
test('throws on invalid range spec', () { test('throws on invalid range spec', () {
expect( expect(
() => repo.revParse('invalid..5aecfa'), () => repo.revParse('invalid..5aecfa'),
throwsA(isA<LibGit2Error>()), throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"revspec 'invalid' not found",
),
),
); );
expect( expect(
() => repo.revParse('master........5aecfa'), () => repo.revParse('master........5aecfa'),
throwsA(isA<LibGit2Error>()), throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"failed to parse revision specifier - Invalid pattern '.....5aecfa'",
),
),
); );
}); });
}); });

View file

@ -1,3 +1,4 @@
import 'dart:ffi';
import 'dart:io'; import 'dart:io';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:libgit2dart/libgit2dart.dart'; import 'package:libgit2dart/libgit2dart.dart';
@ -25,6 +26,25 @@ void main() {
}); });
group('RevWalk', () { group('RevWalk', () {
test('successfully initializes', () {
final walker = RevWalk(repo);
expect(walker, isA<RevWalk>());
walker.free();
});
test('throws when trying to initialize and error occurs', () {
expect(
() => RevWalk(Repository(nullptr)),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'repo'",
),
),
);
});
test('returns list of commits with default sorting', () { test('returns list of commits with default sorting', () {
final walker = RevWalk(repo); final walker = RevWalk(repo);
final start = Oid.fromSHA(repo: repo, sha: log.first); final start = Oid.fromSHA(repo: repo, sha: log.first);
@ -88,11 +108,9 @@ void main() {
test('successfully hides commit and its ancestors', () { test('successfully hides commit and its ancestors', () {
final walker = RevWalk(repo); final walker = RevWalk(repo);
final start = Oid.fromSHA(repo: repo, sha: log.first);
final oidToHide = Oid.fromSHA(repo: repo, sha: log[2]);
walker.push(start); walker.push(repo[log.first]);
walker.hide(oidToHide); walker.hide(repo[log[2]]);
final commits = walker.walk(); final commits = walker.walk();
expect(commits.length, 2); expect(commits.length, 2);
@ -103,6 +121,23 @@ void main() {
walker.free(); walker.free();
}); });
test('throws when trying to hide commit oid and error occurs', () {
final walker = RevWalk(repo);
expect(
() => walker.hide(repo['0' * 40]),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"odb: cannot read object: null OID cannot exist",
),
),
);
walker.free();
});
test('successfully resets walker', () { test('successfully resets walker', () {
final walker = RevWalk(repo); final walker = RevWalk(repo);
final start = Oid.fromSHA(repo: repo, sha: log.first); final start = Oid.fromSHA(repo: repo, sha: log.first);
@ -134,5 +169,23 @@ void main() {
} }
walker.free(); walker.free();
}); });
test('throws when trying to add new root for traversal and error occurs',
() {
final walker = RevWalk(repo);
expect(
() => walker.push(repo['0' * 40]),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"odb: cannot read object: null OID cannot exist",
),
),
);
walker.free();
});
}); });
} }

View file

@ -25,6 +25,34 @@ void main() {
expect(signature, isA<Signature>()); expect(signature, isA<Signature>());
}); });
test('throws when trying to create with empty name and email', () {
expect(
() => Signature.create(name: '', email: '', time: 0),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"failed to parse signature - Signature cannot have an empty name or email",
),
),
);
});
test(
'throws when trying to create with empty name and email and default time',
() {
expect(
() => Signature.create(name: '', email: ''),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"failed to parse signature - Signature cannot have an empty name or email",
),
),
);
});
test('successfully creates without provided time and offset', () { test('successfully creates without provided time and offset', () {
final sig = Signature.create(name: 'Name', email: 'email@example.com'); final sig = Signature.create(name: 'Name', email: 'email@example.com');
expect(sig, isA<Signature>()); expect(sig, isA<Signature>());

View file

@ -1,3 +1,4 @@
import 'dart:ffi';
import 'dart:io'; import 'dart:io';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:libgit2dart/libgit2dart.dart'; import 'package:libgit2dart/libgit2dart.dart';
@ -34,6 +35,19 @@ void main() {
expect(repo.status.isEmpty, true); expect(repo.status.isEmpty, true);
}); });
test('throws when trying to save and error occurs', () {
expect(
() => Repository(nullptr).createStash(stasher: stasher),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'repo'",
),
),
);
});
test('successfully saves changes to stash including ignored', () { test('successfully saves changes to stash including ignored', () {
final swpPath = File('${tmpDir.path}/some.swp'); final swpPath = File('${tmpDir.path}/some.swp');
swpPath.writeAsStringSync('ignored'); swpPath.writeAsStringSync('ignored');
@ -78,6 +92,19 @@ void main() {
expect(repo.status, contains('file')); expect(repo.status, contains('file'));
}); });
test('successfully applies changes from stash with paths provided', () {
File('${tmpDir.path}/file').writeAsStringSync(
'edit',
mode: FileMode.append,
);
repo.createStash(stasher: stasher);
expect(repo.status.isEmpty, true);
repo.applyStash(paths: ['file']);
expect(repo.status, contains('file'));
});
test('successfully applies changes from stash including index changes', () { test('successfully applies changes from stash including index changes', () {
File('${tmpDir.path}/stash.this').writeAsStringSync('stash'); File('${tmpDir.path}/stash.this').writeAsStringSync('stash');
final index = repo.index; final index = repo.index;
@ -95,6 +122,26 @@ void main() {
index.free(); index.free();
}); });
test('throws when trying to apply with wrong index', () {
File('${tmpDir.path}/file').writeAsStringSync(
'edit',
mode: FileMode.append,
);
repo.createStash(stasher: stasher);
expect(
() => repo.applyStash(index: 10),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"no stashed state at position 10",
),
),
);
});
test('successfully drops stash', () { test('successfully drops stash', () {
File('${tmpDir.path}/file').writeAsStringSync( File('${tmpDir.path}/file').writeAsStringSync(
'edit', 'edit',
@ -103,10 +150,30 @@ void main() {
repo.createStash(stasher: stasher); repo.createStash(stasher: stasher);
final stash = repo.stashes.first; final stash = repo.stashes.first;
repo.dropStash(stash.index); repo.dropStash(index: stash.index);
expect(() => repo.applyStash(), throwsA(isA<LibGit2Error>())); expect(() => repo.applyStash(), throwsA(isA<LibGit2Error>()));
}); });
test('throws when trying to drop with wrong index', () {
File('${tmpDir.path}/file').writeAsStringSync(
'edit',
mode: FileMode.append,
);
repo.createStash(stasher: stasher);
expect(
() => repo.dropStash(index: 10),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"no stashed state at position 10",
),
),
);
});
test('successfully pops from stash', () { test('successfully pops from stash', () {
File('${tmpDir.path}/file').writeAsStringSync( File('${tmpDir.path}/file').writeAsStringSync(
'edit', 'edit',
@ -119,6 +186,18 @@ void main() {
expect(() => repo.applyStash(), throwsA(isA<LibGit2Error>())); expect(() => repo.applyStash(), throwsA(isA<LibGit2Error>()));
}); });
test('successfully pops from stash with provided path', () {
File('${tmpDir.path}/file').writeAsStringSync(
'edit',
mode: FileMode.append,
);
repo.createStash(stasher: stasher);
repo.popStash(paths: ['file']);
expect(repo.status, contains('file'));
expect(() => repo.applyStash(), throwsA(isA<LibGit2Error>()));
});
test('successfully pops from stash including index changes', () { test('successfully pops from stash including index changes', () {
File('${tmpDir.path}/stash.this').writeAsStringSync('stash'); File('${tmpDir.path}/stash.this').writeAsStringSync('stash');
final index = repo.index; final index = repo.index;
@ -136,6 +215,26 @@ void main() {
index.free(); index.free();
}); });
test('throws when trying to pop with wrong index', () {
File('${tmpDir.path}/file').writeAsStringSync(
'edit',
mode: FileMode.append,
);
repo.createStash(stasher: stasher);
expect(
() => repo.popStash(index: 10),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"no stashed state at position 10",
),
),
);
});
test('returns list of stashes', () { test('returns list of stashes', () {
File('${tmpDir.path}/file').writeAsStringSync( File('${tmpDir.path}/file').writeAsStringSync(
'edit', 'edit',

View file

@ -1,3 +1,4 @@
import 'dart:ffi';
import 'dart:io'; import 'dart:io';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:libgit2dart/libgit2dart.dart'; import 'package:libgit2dart/libgit2dart.dart';
@ -43,6 +44,19 @@ void main() {
submodule.free(); submodule.free();
}); });
test('throws when trying to lookup and submodule not found', () {
expect(
() => repo.lookupSubmodule('not/there'),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"no submodule named 'not/there'",
),
),
);
});
test('successfully inits and updates', () { test('successfully inits and updates', () {
final submoduleFilePath = '${repo.workdir}$testSubmodule/master.txt'; final submoduleFilePath = '${repo.workdir}$testSubmodule/master.txt';
expect(File(submoduleFilePath).existsSync(), false); expect(File(submoduleFilePath).existsSync(), false);
@ -62,6 +76,19 @@ void main() {
expect(File(submoduleFilePath).existsSync(), true); expect(File(submoduleFilePath).existsSync(), true);
}); });
test('throws when trying to update not initialized submodule', () {
expect(
() => repo.updateSubmodule(submodule: testSubmodule),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"submodule is not initialized",
),
),
);
});
test('successfully opens repository for a submodule', () { test('successfully opens repository for a submodule', () {
final submodule = repo.lookupSubmodule(testSubmodule); final submodule = repo.lookupSubmodule(testSubmodule);
repo.initSubmodule(submodule: testSubmodule); repo.initSubmodule(submodule: testSubmodule);
@ -81,6 +108,24 @@ void main() {
submodule.free(); submodule.free();
}); });
test('throws when trying to open repository for not initialized submodule',
() {
final submodule = repo.lookupSubmodule(testSubmodule);
expect(
() => submodule.open(),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
contains("failed to resolve path"),
),
),
);
submodule.free();
});
test('successfully adds submodule', () { test('successfully adds submodule', () {
final submodule = repo.addSubmodule( final submodule = repo.addSubmodule(
url: submoduleUrl, url: submoduleUrl,
@ -96,6 +141,38 @@ void main() {
submodule.free(); submodule.free();
}); });
test('throws when trying to add submodule with wrong url', () {
expect(
() => repo.addSubmodule(
url: 'https://wrong.url/',
path: 'test',
),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
'failed to resolve address for wrong.url: Name or service not known',
),
),
);
});
test('throws when trying to add submodule and error occurs', () {
expect(
() => Repository(nullptr).addSubmodule(
url: 'https://wrong.url/',
path: 'test',
),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'repo'",
),
),
);
});
test('successfully sets configuration values', () { test('successfully sets configuration values', () {
final submodule = repo.lookupSubmodule(testSubmodule); final submodule = repo.lookupSubmodule(testSubmodule);
expect(submodule.url, submoduleUrl); expect(submodule.url, submoduleUrl);

View file

@ -1,3 +1,4 @@
import 'dart:ffi';
import 'dart:io'; import 'dart:io';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:libgit2dart/libgit2dart.dart'; import 'package:libgit2dart/libgit2dart.dart';
@ -27,6 +28,32 @@ void main() {
expect(tag, isA<Tag>()); expect(tag, isA<Tag>());
}); });
test('throws when trying to lookup tag for invalid oid', () {
expect(
() => repo.lookupTag(repo['0' * 40]),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"odb: cannot read object: null OID cannot exist",
),
),
);
});
test('throws when trying to get target of a tag and error occurs', () {
expect(
() => Tag(nullptr).target,
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 't'",
),
),
);
});
test('returns correct values', () { test('returns correct values', () {
final signature = Signature.create( final signature = Signature.create(
name: 'Aleksey Kulikov', name: 'Aleksey Kulikov',
@ -179,15 +206,79 @@ void main() {
signature.free(); signature.free();
}); });
test('throws when trying to create tag with invalid name', () {
expect(
() => repo.createTag(
tagName: '',
target: repo['9c78c21'],
targetType: GitObject.any,
tagger: Signature(nullptr),
message: '',
),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: '!create_tag_annotation || (tagger && message)'",
),
),
);
});
test('throws when trying to create tag with invalid target', () {
expect(
() => repo.createTag(
tagName: '',
target: repo['0' * 40],
targetType: GitObject.any,
tagger: Signature(nullptr),
message: '',
),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"odb: cannot read object: null OID cannot exist",
),
),
);
});
test('returns list of tags in repository', () { test('returns list of tags in repository', () {
expect(Tag.list(repo), ['v0.1', 'v0.2']); expect(Tag.list(repo), ['v0.1', 'v0.2']);
}); });
test('throws when trying to get list of tags and error occurs', () {
expect(
() => Repository(nullptr).tags,
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'repo'",
),
),
);
});
test('successfully deletes tag', () { test('successfully deletes tag', () {
expect(repo.tags, ['v0.1', 'v0.2']); expect(repo.tags, ['v0.1', 'v0.2']);
repo.deleteTag('v0.2'); repo.deleteTag('v0.2');
expect(repo.tags, ['v0.1']); expect(repo.tags, ['v0.1']);
}); });
test('throws when trying to delete non existing tag', () {
expect(
() => repo.deleteTag('not.there'),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"reference 'refs/tags/not.there' not found",
),
),
);
});
}); });
} }

View file

@ -29,6 +29,19 @@ void main() {
expect(tree.toString(), contains('Tree{')); expect(tree.toString(), contains('Tree{'));
}); });
test('throws when looking up tree for invalid oid', () {
expect(
() => repo.lookupTree(repo['0' * 40]),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"odb: cannot read object: null OID cannot exist",
),
),
);
});
test('returns correct values', () { test('returns correct values', () {
expect(tree.length, 4); expect(tree.length, 4);
expect(tree.entries.first.oid.sha, fileSHA); expect(tree.entries.first.oid.sha, fileSHA);

View file

@ -1,3 +1,4 @@
import 'dart:ffi';
import 'dart:io'; import 'dart:io';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:libgit2dart/libgit2dart.dart'; import 'package:libgit2dart/libgit2dart.dart';
@ -39,6 +40,19 @@ void main() {
builder.free(); builder.free();
}); });
test('throws when trying to initialize and error occurs', () {
expect(
() => TreeBuilder(repo: Repository(nullptr)),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'repo'",
),
),
);
});
test('clears all the entries in the builder', () { test('clears all the entries in the builder', () {
final builder = TreeBuilder(repo: repo, tree: tree); final builder = TreeBuilder(repo: repo, tree: tree);
@ -65,6 +79,42 @@ void main() {
builder.free(); builder.free();
}); });
test('throws when trying to add entry with invalid name or invalid oid',
() {
final builder = TreeBuilder(repo: repo);
expect(
() => builder.add(
filename: '',
oid: repo['0' * 40],
filemode: GitFilemode.blob,
),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"failed to insert entry: invalid name for a tree entry - ",
),
),
);
expect(
() => builder.add(
filename: 'some.file',
oid: repo['0' * 40],
filemode: GitFilemode.blob,
),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"failed to insert entry: invalid null OID - some.file",
),
),
);
builder.free();
});
test('successfully removes an entry', () { test('successfully removes an entry', () {
final builder = TreeBuilder(repo: repo, tree: tree); final builder = TreeBuilder(repo: repo, tree: tree);
@ -76,5 +126,22 @@ void main() {
builder.free(); builder.free();
}); });
test('throws when trying to remove entry that is not in the tree', () {
final builder = TreeBuilder(repo: repo);
expect(
() => builder.remove('not.there'),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"failed to remove entry: file isn't in the tree - not.there",
),
),
);
builder.free();
});
}); });
} }

View file

@ -1,3 +1,4 @@
import 'dart:ffi';
import 'dart:io'; import 'dart:io';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:libgit2dart/libgit2dart.dart'; import 'package:libgit2dart/libgit2dart.dart';
@ -85,6 +86,35 @@ void main() {
worktree.free(); worktree.free();
}); });
test('throws when trying to create worktree with invalid name or path', () {
expect(
() => repo.createWorktree(
name: '',
path: worktreeDir.path,
),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
contains('failed to make directory'),
),
),
);
expect(
() => repo.createWorktree(
name: 'name',
path: '',
),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
'attempt to create empty path: Invalid argument',
),
),
);
});
test('successfully lookups worktree', () { test('successfully lookups worktree', () {
final worktree = repo.createWorktree( final worktree = repo.createWorktree(
name: worktreeName, name: worktreeName,
@ -100,6 +130,19 @@ void main() {
worktree.free(); worktree.free();
}); });
test('throws when trying to lookup and error occurs', () {
expect(
() => Worktree.lookup(repo: Repository(nullptr), name: 'name'),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'repo'",
),
),
);
});
test('successfully locks and unlocks worktree', () { test('successfully locks and unlocks worktree', () {
final worktree = repo.createWorktree( final worktree = repo.createWorktree(
name: worktreeName, name: worktreeName,
@ -136,5 +179,18 @@ void main() {
worktree.free(); worktree.free();
}); });
test('throws when trying get list of worktrees and error occurs', () {
expect(
() => Worktree.list(Repository(nullptr)),
throwsA(
isA<LibGit2Error>().having(
(e) => e.toString(),
'error',
"invalid argument: 'repo'",
),
),
);
});
}); });
} }