Skip to content

Commit

Permalink
Add a utility to classify as file as text/binary.
Browse files Browse the repository at this point in the history
For use to help automatically set the internal file attributes bits.
  • Loading branch information
hainesr committed Jan 11, 2022
1 parent 90728d7 commit cc3e0f9
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
27 changes: 27 additions & 0 deletions lib/zip/util/file_classifier.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
module Zip
module Util
class FileClassifier
CNTRL_LIST = [(0..6), (14..25), (28..31)].map(&:to_a).reduce(&:+)
ALLOW_LIST = [9, 10, 13] + (32..255).to_a

def self.classify(buffer, length = 256)
has_allowed = false
buffer[0...length].each_byte do |b|
return :binary if CNTRL_LIST.include?(b)

has_allowed = true if ALLOW_LIST.include?(b)
end

has_allowed ? :text : :binary
end

def self.text?(buffer)
classify(buffer) == :text
end

def self.binary?(buffer)
classify(buffer) == :binary
end
end
end
end
32 changes: 32 additions & 0 deletions test/util/file_classifier_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
require 'test_helper'
require 'zip/util/file_classifier'

class FileClassifierTest < MiniTest::Test
def test_classify_data
assert(::Zip::Util::FileClassifier.text?('Hello, World!'))
assert(::Zip::Util::FileClassifier.binary?(''))
assert(::Zip::Util::FileClassifier.binary?("\x00"))
assert(::Zip::Util::FileClassifier.binary?("\x1b\x00"))
assert(::Zip::Util::FileClassifier.binary?("\x1b"))
assert(::Zip::Util::FileClassifier.text?("Hello, World\x21"))
assert(::Zip::Util::FileClassifier.binary?("Hello, World\x00"))
assert(::Zip::Util::FileClassifier.text?("Hello, World\x1b"))
assert(::Zip::Util::FileClassifier.text?("\xab"))
end

def test_detect_text_file
data = ::File.read('test/data/file1.txt')
assert_equal(:text, ::Zip::Util::FileClassifier.classify(data))
assert_equal(:text, ::Zip::Util::FileClassifier.classify(data, 2_048))
refute(::Zip::Util::FileClassifier.binary?(data))
assert(::Zip::Util::FileClassifier.text?(data))
end

def test_detect_binary_file
data = ::File.binread('test/data/test.xls', 256)
assert_equal(:binary, ::Zip::Util::FileClassifier.classify(data))
assert_equal(:binary, ::Zip::Util::FileClassifier.classify(data, 64))
assert(::Zip::Util::FileClassifier.binary?(data))
refute(::Zip::Util::FileClassifier.text?(data))
end
end

0 comments on commit cc3e0f9

Please sign in to comment.