Sha256: 550f41e394dfb2dccb07182da4e91e7e83de4d18beb38c4994212c4600ef27bb

Contents?: true

Size: 1.49 KB

Versions: 21

Compression:

Stored size: 1.49 KB

Contents

# frozen_string_literal: true

module HTTPX
  module Plugins::Multipart
    module MimeTypeDetector
      module_function

      DEFAULT_MIMETYPE = "application/octet-stream"

      # inspired by https://github.com/shrinerb/shrine/blob/master/lib/shrine/plugins/determine_mime_type.rb
      if defined?(MIME::Types)

        def call(_file, filename)
          mime = MIME::Types.of(filename).first
          mime.content_type if mime
        end

      elsif defined?(MimeMagic)

        def call(file, *)
          mime = MimeMagic.by_magic(file)
          mime.type if mime
        end

      elsif system("which file", out: File::NULL)
        require "open3"

        def call(file, *)
          return if file.eof? # file command returns "application/x-empty" for empty files

          Open3.popen3(*%w[file --mime-type --brief -]) do |stdin, stdout, stderr, thread|
            begin
              ::IO.copy_stream(file, stdin.binmode)
            rescue Errno::EPIPE
            end
            file.rewind
            stdin.close

            status = thread.value

            # call to file command failed
            if status.nil? || !status.success?
              $stderr.print(stderr.read)
            else

              output = stdout.read.strip

              if output.include?("cannot open")
                $stderr.print(output)
              else
                output
              end
            end
          end
        end

      else

        def call(*); end

      end
    end
  end
end

Version data entries

21 entries across 21 versions & 1 rubygems

Version Path
httpx-0.11.0 lib/httpx/plugins/multipart/mime_type_detector.rb