Skip to content

Commit 4591e76

Browse files
author
Edward Thomson
committed
blob: identify binary content
Introduce `git_blob_data_is_binary` to examine a blob's data, instead of the blob itself. A replacement for `git_buf_is_binary`.
1 parent 12b53eb commit 4591e76

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

include/git2/blob.h

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,18 @@ GIT_EXTERN(int) git_blob_create_from_buffer(
284284
*/
285285
GIT_EXTERN(int) git_blob_is_binary(const git_blob *blob);
286286

287+
/**
288+
* Determine if the given content is most certainly binary or not;
289+
* this is the same mechanism used by `git_blob_is_binary` but only
290+
* looking at raw data.
291+
*
292+
* @param data The blob data which content should be analyzed
293+
* @param len The length of the data
294+
* @return 1 if the content of the blob is detected
295+
* as binary; 0 otherwise.
296+
*/
297+
GIT_EXTERN(int) git_blob_data_is_binary(const char *data, size_t len);
298+
287299
/**
288300
* Create an in-memory copy of a blob. The copy must be explicitly
289301
* free'd or it will leak.

src/blob.c

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -404,6 +404,15 @@ int git_blob_is_binary(const git_blob *blob)
404404
return git_str_is_binary(&content);
405405
}
406406

407+
int git_blob_data_is_binary(const char *str, size_t len)
408+
{
409+
git_str content = GIT_STR_INIT;
410+
411+
git_str_attach_notowned(&content, str, len);
412+
413+
return git_str_is_binary(&content);
414+
}
415+
407416
int git_blob_filter_options_init(
408417
git_blob_filter_options *opts,
409418
unsigned int version)

tests/diff/blob.c

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -604,12 +604,28 @@ void test_diff_blob__can_correctly_detect_a_binary_blob_as_binary(void)
604604
cl_assert_equal_i(true, git_blob_is_binary(alien));
605605
}
606606

607+
void test_diff_blob__can_correctly_detect_binary_blob_data_as_binary(void)
608+
{
609+
/* alien.png */
610+
const char *content = git_blob_rawcontent(alien);
611+
size_t len = (size_t)git_blob_rawsize(alien);
612+
cl_assert_equal_i(true, git_blob_data_is_binary(content, len));
613+
}
614+
607615
void test_diff_blob__can_correctly_detect_a_textual_blob_as_non_binary(void)
608616
{
609617
/* tests/resources/attr/root_test4.txt */
610618
cl_assert_equal_i(false, git_blob_is_binary(d));
611619
}
612620

621+
void test_diff_blob__can_correctly_detect_textual_blob_data_as_non_binary(void)
622+
{
623+
/* tests/resources/attr/root_test4.txt */
624+
const char *content = git_blob_rawcontent(d);
625+
size_t len = (size_t)git_blob_rawsize(d);
626+
cl_assert_equal_i(false, git_blob_data_is_binary(content, len));
627+
}
628+
613629
/*
614630
* git_diff_blob_to_buffer tests
615631
*/

0 commit comments

Comments
 (0)