Created
October 3, 2012 16:21
-
-
Save jtzero/3828006 to your computer and use it in GitHub Desktop.
Ruby realpath returns the unc path if available for mapped drive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# * *author* : jtzero | |
# * *version* : 1.2.3 | |
# * *description* : returns the unc path of a file when using realdir | |
# | |
require 'win32api' | |
class IO | |
WNetGetConnection = begin | |
Win32API.new("mpr.dll", "WNetGetConnection", ['P','P','P'], 'L') | |
rescue #if not windows just return 0 | |
lambda {|locate, remote, size| remote = local; next 0 } | |
end | |
# wrapper for WNetGetConnection | |
# * *args* : | |
# - +local_name+ -> the name on this computer | |
# - +str_size=1024+ -> the size of the empty string to be passed to WNetGetConnection | |
# - +fail_on_not_found=false+ -> fail if there is no network connection for that local_name | |
def self.wnet_get_connection(local_name, str_size=1024, fail_on_not_found=false) | |
remote_name = "\0" * str_size | |
error_code = WNetGetConnection.call(local_name, remote_name, [str_size].pack('L')) | |
raise("Windows error #{error_code} consult http://msdn.microsoft.com 'System Error Codes'") unless error_code == 0 or !(fail_on_not_found and error_code == 2250) | |
return remote_name.rstrip.gsub('\\', '/') unless remote_name.rstrip.empty? # I got nothin, return nil | |
end | |
end | |
class File | |
class << self | |
# windows-only | |
# * *args* : | |
# - +drive+ -> the drive to check, if nothing is given it will get it | |
def on_network_drive?(drive=get_drive_name(Dir.orig_pwd)) | |
wnet_get_connection(drive) | |
end | |
# windows-only | |
# * *args* : | |
# - +path+ -> | |
def get_unc_path(path) | |
unc_path = on_network_drive?(get_drive_name(path)) | |
unc_path + path.split(/(:)/, 2).last if unc_path | |
end | |
# | |
# | |
# modded for windows unc_path | |
alias_method :orig_realpath, :realpath | |
def realpath(path, dir_string=nil) | |
get_unc_path(path) || orig_realpath(path, dir_string) | |
end | |
private | |
# windows-only will return whole path otherwise | |
# * *args* : | |
# - path -> the path that the derive will be extracted from | |
# * *returns* : String, the drive or the whole path | |
def get_drive_name(path) | |
path.split(/(:)/, 2)[0..1].join | |
end | |
end | |
end | |
#puts File.realpath Dir.pwd |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment