From f651eb7d3cd6a91f5beddf85c5dbd3f850538a69 Mon Sep 17 00:00:00 2001 From: Gabriel Vasile Date: Thu, 11 Nov 2021 19:47:56 +0200 Subject: [PATCH 1/2] Add regression test for partial JSON detection For #198 --- internal/magic/magic_test.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 internal/magic/magic_test.go diff --git a/internal/magic/magic_test.go b/internal/magic/magic_test.go new file mode 100644 index 00000000..f89aff84 --- /dev/null +++ b/internal/magic/magic_test.go @@ -0,0 +1,20 @@ +package magic + +import "testing" + +var magicTests = []struct { + raw string + limit uint32 + res bool + detector Detector +}{ + {`["an incomplete JSON array`, 0, false, JSON}, +} + +func TestMagic(t *testing.T) { + for i, tt := range magicTests { + if got := tt.detector([]byte(tt.raw), tt.limit); got != tt.res { + t.Errorf("Detector %d error: expected: %t; got: %t", i, tt.res, got) + } + } +} From 9fdffeb8b24585ba997a829717430c82995c6608 Mon Sep 17 00:00:00 2001 From: Gabriel Vasile Date: Thu, 11 Nov 2021 23:48:26 +0200 Subject: [PATCH 2/2] Fix JSON returned for partial documents when readLimit=0 For #198 --- internal/magic/text.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/internal/magic/text.go b/internal/magic/text.go index 026c6aad..40bfb190 100644 --- a/internal/magic/text.go +++ b/internal/magic/text.go @@ -155,12 +155,14 @@ func Php(raw []byte, limit uint32) bool { // JSON matches a JavaScript Object Notation file. func JSON(raw []byte, limit uint32) bool { raw = trimLWS(raw) - if len(raw) == 0 || (raw[0] != '[' && raw[0] != '{') { + // #175 A single JSON string, number or bool is not considered JSON. + // JSON objects and arrays are reported as JSON. + if len(raw) < 2 || (raw[0] != '[' && raw[0] != '{') { return false } parsed, err := json.Scan(raw) // If the full file content was provided, check there is no error. - if len(raw) < int(limit) { + if limit == 0 || len(raw) < int(limit) { return err == nil }