Class: File
- Inherits:
-
Object
- Object
- File
- Defined in:
- lib/planter/file.rb
Overview
File helpers
Constant Summary collapse
- TEXT_TYPES =
Allowable text file types
%w[text ansi xml json yaml csv empty].freeze
Class Method Summary collapse
-
.binary?(name) ⇒ Boolean
Test if file is binary.
-
.second_test(name) ⇒ Boolean
Secondary test with file command.
-
.text?(name) ⇒ Boolean
Test if file is text.
- .text_type?(name) ⇒ Boolean
-
.third_test(name) ⇒ Boolean
Tertiary test for binary file.
Class Method Details
.binary?(name) ⇒ Boolean
Test if file is binary
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/planter/file.rb', line 25 def self.binary?(name) return true if name.nil? || name.empty? || !File.exist?(name) ascii = control = binary = 0 bytes = File.open(name, 'rb') { |io| io.read(1024) } return true if bytes.nil? || bytes.empty? bytes.each_byte do |bt| case bt when 0...32 control += 1 when 32...128 ascii += 1 else binary += 1 end end first_test = binary.to_f / ascii > 0.05 first_test || second_test(name) end |
.second_test(name) ⇒ Boolean
Secondary test with file command
59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/planter/file.rb', line 59 def self.second_test(name) if TTY::Which.exist?('file') file_type, status = Open3.capture2e('file', name) file_type = file_type.split(':')[1..-1].join(':').strip if file_type =~ /Apple binary property list/ && TTY::Which.exist?('plutil') `plutil -convert xml1 "#{name}"` File.binary?(name) else status.success? && !text_type?(file_type) end else false end end |
.text?(name) ⇒ Boolean
Test if file is text
14 15 16 |
# File 'lib/planter/file.rb', line 14 def self.text?(name) !binary?(name) end |
.text_type?(name) ⇒ Boolean
90 91 92 |
# File 'lib/planter/file.rb', line 90 def self.text_type?(name) TEXT_TYPES.any? { |type| name.downcase.include?(type) } || name.empty? end |
.third_test(name) ⇒ Boolean
Tertiary test for binary file
81 82 83 84 85 86 87 88 |
# File 'lib/planter/file.rb', line 81 def self.third_test(name) if TTY::Which.exist?('mdls') file_type, status = Open3.capture2e('mdls', '-name', 'kMDItemContentTypeTree', name) status.success? && !text_type?(file_type) else false end end |