Created
March 8, 2013 23:58
-
-
Save aprescott/5121481 to your computer and use it in GitHub Desktop.
Permissions and umask
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
def permissions_string(integer) | |
triplet_to_string = lambda { |x, s| x.tr("01", "-#{s}") } | |
integer.to_s(2).rjust(9, "0").chars.each_slice(3).map do |r, w, x| | |
[ | |
triplet_to_string[r, "r"], | |
triplet_to_string[w, "w"], | |
triplet_to_string[x, "x"] | |
].join("") | |
end.join("") | |
end | |
permissions_string 0777 | |
#=> rwxrwxrwx | |
permissions_string 0205 | |
#=> -w----r-x | |
permissions_string 0757 | |
#=> rwxr-xrwx | |
permissions_string 0202 | |
# -w-----w- | |
permissions_string 0777 | |
# rwxrwxrwx | |
# use 0202 as the mask to substract permissions off 0777 | |
permissions_string(0777 & ~0202) | |
# r-xrwxrwx | |
# = | |
# rwxrwxrwx masked with | |
# -w-----w- | |
# 0777 & ~mask is useful with File.umask to get the default | |
# permissions as if you'd used `touch` | |
permissions_string File.umask | |
# ----w--w- (may differ in output for you) | |
permissions_string(0777 & ~File.umask) | |
# rwxr-xr-x | |
# also masking out executable bits, if creating a new file. | |
# (general executable permissions for files outside of your | |
# control is a bad idea) | |
permissions_string(0777 & ~0111 & ~File.umask) | |
# rwxr--r-- | |
File.open("/tmp/foo", "w", 0777 & ~0111 & ~File.umask) {} | |
# interested only in the last 3 triples | |
file_mode = File.stat("/tmp/foo").mode & 0777 | |
permissions_string(file_mode) | |
# rw-r--r-- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment