DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Code To Determine If File System Is Case Sensitive In Ruby (esp. OS X)

10.02.2011
| 2939 views |
  • submit to reddit
        // this code will add normcase to Pathname and File in ruby correctly (only the OS X part has been tested)


  module NormCase
    require 'rbconfig'
    require 'pathname'
    require 'tempfile'
    require 'tmpdir'
    def case_sensitive(path=nil) #if not given  will use tempfile on OS X
      case RbConfig::CONFIG["host_os"] 
      when /mswin|mingw|cygwin/i #windows is always insensitive
        return false
      when /darwin/i # the trouble maker as only the underlying file system knows and that requires using Cocoa
        require 'osx/cocoa'
        include OSX
        #OSX.require_framework('Foundation') #this would be false as it loaded already
        if ! path then
          tf=Tempfile.new(["Temp","Test"],File(path).dirname)
          path=tf.path
          tf.close
          tf.unlink
        end
        realpath=Pathname(path).parent.realpath().to_s # now we have a full path
        # filesystem is an NSURL for realpath with isDirectory => true
        filesystem = NSURL.FileURLWithPath_isDirectory_(realpath,true)
        #result = [has res., res. value, error value] forKey=>NSURLVolumeSupportsCaseSensitiveNamesKey
        result = filesystem.getResourceValue_forKey_error_(NSURLVolumeSupportsCaseSensitiveNamesKey) 
        return result[1].to_ruby # convert to_ruby because it is an NSCFBoolean (this likely is is false, thanks to Adobe)
      when /sunos|solaris|linux/i #unix types are case sensitive
        return true
      when /vms|os/i #vms or os/2 # TODO: check this but I know that vms and OS/2 are case-insensitive
        return false
      else # freeBSD, OpenBSD, etc #assume they are posix types with case sensitive file systems
        return true
      end
    end

    def normcase(path)
      if ! case_sensitive(path) then
        self.to_s().upcase()
      else
        self.to_s()
      end
    end
  end
  # don't forget to include this to extend Pathname and File
  class Pathname
    include NormCase
  end
  class File
    include NormCase
  end